code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
COMPILE_TIME_ASSERT(sizeof(long)==8);
int main()
{
COMPILE_TIME_ASSERT(sizeof(int)==4);
} | 572Metaprogramming
| 5c
| o4780 |
(defn take-random [n coll]
(->> (repeatedly #(rand-nth coll))
distinct
(take n ,)))
(defn postwalk-fs
"Depth first post-order traversal of form, apply successive fs at each level.
(f1 (map f2 [..]))"
[[f & fs] form]
(f
(if (and (seq fs) (coll? form))
(into (empty form) (map (partial postwalk-fs fs) form))
form)))
(defn neighbors [x y n m pred]
(for [dx (range (Math/max 0 (dec x)) (Math/min n (+ 2 x)))
dy (range (Math/max 0 (dec y)) (Math/min m (+ 2 y)))
:when (pred dx dy)]
[dx dy]))
(defn new-game [n m density]
(let [mines (set (take-random (Math/floor (* n m density)) (range (* n m))))]
(->> (for [y (range m)
x (range n)
:let [neighbor-mines (count (neighbors x y n m #(mines (+ %1 (* %2 n)))))]]
(#(if (mines (+ (* y n) x)) (assoc %:mine true) %) {:value neighbor-mines}))
(partition n ,)
(postwalk-fs [vec vec] ,))))
(defn display [board]
(postwalk-fs [identity println #(condp % nil
:marked \?
:opened (:value %)
\.)] board))
(defn boom [{board:board}]
(postwalk-fs [identity println #(if (:mine %) \* (:value %))] board)
true)
(defn open* [board [[x y] & rest]]
(if-let [value (get-in board [y x:value])]
(recur
(assoc-in board [y x:opened] true)
(if (pos? value)
rest
(concat rest
(neighbors x y (count (first board)) (count board)
#(not (get-in board [%2 %1:opened]))))))
board))
(defn open [board x y]
(let [x (dec x), y (dec y)]
(condp (get-in board [y x]) nil
:mine {:boom true:board board}
:opened board
(open* board [[x y]]))))
(defn mark [board x y]
(let [x (dec x), y (dec y)]
(assoc-in board [y x:marked] (not (get-in board [y x:marked])))))
(defn done? [board]
(if (:boom board)
(boom board)
(do (display board)
(->> (flatten board)
(remove:mine ,)
(every?:opened ,)))))
(defn play [n m density]
(let [board (new-game n m density)]
(println [:mines (count (filter:mine (flatten board)))])
(loop [board board]
(when-not (done? board)
(print ">")
(let [[cmd & xy] (.split #" " (read-line))
[x y] (map #(Integer. %) xy)]
(recur ((if (= cmd "mark") mark open) board x y))))))) | 568Minesweeper game
| 6clojure
| cwi9b |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List; | 567Minimum positive multiple in base 10 using only 0 and 1
| 9java
| jfc7c |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() { | 569Mind boggling card trick
| 0go
| nrpi1 |
(loop for count from 1
for x in '(1 2 3 4 5)
summing x into sum
summing (* x x) into sum-of-squares
finally
(return
(let* ((mean (/ sum count))
(spl-var (- (* count sum-of-squares) (* sum sum)))
(spl-dev (sqrt (/ spl-var (1- count)))))
(values mean spl-var spl-dev)))) | 572Metaprogramming
| 6clojure
| thpfv |
import java.math.BigInteger;
public class PowMod {
public static void main(String[] args){
BigInteger a = new BigInteger(
"2988348162058574136915891421498819466320163312926952423791023078876139");
BigInteger b = new BigInteger(
"2351399303373464486466122544523690094744975233415544072992656881240319");
BigInteger m = new BigInteger("10000000000000000000000000000000000000000");
System.out.println(a.modPow(b, m));
}
} | 566Modular exponentiation
| 9java
| 3b0zg |
struct timeval start, last;
inline int64_t tv_to_u(struct timeval s)
{
return s.tv_sec * 1000000 + s.tv_usec;
}
inline struct timeval u_to_tv(int64_t x)
{
struct timeval s;
s.tv_sec = x / 1000000;
s.tv_usec = x % 1000000;
return s;
}
void draw(int dir, int64_t period, int64_t cur, int64_t next)
{
int len = 40 * (next - cur) / period;
int s, i;
if (len > 20) len = 40 - len;
s = 20 + (dir ? len : -len);
printf();
for (i = 0; i <= 40; i++) putchar(i == 20 ? '|': i == s ? '
}
void beat(int delay)
{
struct timeval tv = start;
int dir = 0;
int64_t d = 0, corr = 0, slp, cur, next = tv_to_u(start) + delay;
int64_t draw_interval = 20000;
printf();
while (1) {
gettimeofday(&tv, 0);
slp = next - tv_to_u(tv) - corr;
usleep(slp);
gettimeofday(&tv, 0);
putchar(7);
fflush(stdout);
printf(,
(int)d, (int)corr);
dir = !dir;
cur = tv_to_u(tv);
d = cur - next;
corr = (corr + d) / 2;
next += delay;
while (cur + d + draw_interval < next) {
usleep(draw_interval);
gettimeofday(&tv, 0);
cur = tv_to_u(tv);
draw(dir, delay, cur, next);
fflush(stdout);
}
}
}
int main(int c, char**v)
{
int bpm;
if (c < 2 || (bpm = atoi(v[1])) <= 0) bpm = 60;
if (bpm > 600) {
fprintf(stderr, , bpm);
exit(1);
}
gettimeofday(&start, 0);
last = start;
beat(60 * 1000000 / bpm);
return 0;
} | 573Metronome
| 5c
| 1y9pj |
import System.Random (randomRIO)
import Data.List (partition)
import Data.Monoid ((<>))
main :: IO [Int]
main = do
ns <- knuthShuffle [1 .. 52]
let (rs_, bs_, discards) = threeStacks (rb <$> ns)
nSwap <- randomRIO (1, min (length rs_) (length bs_))
let (rs, bs) = exchange nSwap rs_ bs_
let rrs = filter ('R' ==) rs
let bbs = filter ('B' ==) bs
putStrLn $
unlines
[ "Discarded: " <> discards
, "Swapped: " <> show nSwap
, "Red pile: " <> rs
, "Black pile: " <> bs
, rrs <> " = Red cards in the red pile"
, bbs <> " = Black cards in the black pile"
, show $ length rrs == length bbs
]
return ns
rb :: Int -> Char
rb n
| even n = 'R'
| otherwise = 'B'
threeStacks :: String -> (String, String, String)
threeStacks = go ([], [], [])
where
go tpl [] = tpl
go (rs, bs, ds) [x] = (rs, bs, x: ds)
go (rs, bs, ds) (x:y:xs)
| 'R' == x = go (y: rs, bs, x: ds) xs
| otherwise = go (rs, y: bs, x: ds) xs
exchange :: Int -> [a] -> [a] -> ([a], [a])
exchange n xs ys =
let [xs_, ys_] = splitAt n <$> [xs, ys]
in (fst ys_ <> snd xs_, fst xs_ <> snd ys_)
knuthShuffle :: [a] -> IO [a]
knuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> randoms (length xs)
randoms :: Int -> IO [Int]
randoms x = traverse (randomRIO . (,) 0) [1 .. (pred x)]
swapElems :: (Int, Int) -> [a] -> [a]
swapElems (i, j) xs
| i == j = xs
| otherwise = replaceAt j (xs !! i) $ replaceAt i (xs !! j) xs
replaceAt :: Int -> a -> [a] -> [a]
replaceAt i c l =
let (a, b) = splitAt i l
in a ++ c: drop 1 b | 569Mind boggling card trick
| 8haskell
| u0fv2 |
package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for%s ratio, where b =%d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d,%d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(",%d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to%d dp after%2d iteration%s:%s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
} | 574Metallic ratios
| 0go
| htzjq |
null | 566Modular exponentiation
| 11kotlin
| nreij |
class Modulo
include Comparable
def initialize(n = 0, m = 13)
@n, @m = n % m, m
end
def to_i
@n
end
def <=>(other_n)
@n <=> other_n.to_i
end
[:+,:-,:*,:**].each do |meth|
define_method(meth) { |other_n| Modulo.new(@n.send(meth, other_n.to_i), @m) }
end
def coerce(numeric)
[numeric, @n]
end
end
x, y = Modulo.new(10), Modulo.new(20)
p x > y
p x == y
p [x,y].sort
p x + y
p 2 + y
p y + 2
p x**100 + x +1 | 564Modular arithmetic
| 14ruby
| 58muj |
>>> size = 12
>>> width = len(str(size**2))
>>> for row in range(-1,size+1):
if row==0:
print(*width + +*((width+1)*size-1))
else:
print(.join(% ((width,) + ((,) if row==-1 and col==0
else (row,) if row>0 and col==0
else (col,) if row==-1
else (,) if row>col
else (row*col,)))
for col in range(size+1)))
x 1 2 3 4 5 6 7 8 9 10 11 12
1 1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 9 12 15 18 21 24 27 30 33 36
4 16 20 24 28 32 36 40 44 48
5 25 30 35 40 45 50 55 60
6 36 42 48 54 60 66 72
7 49 56 63 70 77 84
8 64 72 80 88 96
9 81 90 99 108
10 100 110 120
11 121 132
12 144
>>> | 560Multiplication tables
| 3python
| svwq9 |
(() => {
'use strict';
const main = () => {
const | 569Mind boggling card trick
| 10javascript
| vsd25 |
class MetallicRatios {
private static List<String> names = new ArrayList<>()
static {
names.add("Platinum")
names.add("Golden")
names.add("Silver")
names.add("Bronze")
names.add("Copper")
names.add("Nickel")
names.add("Aluminum")
names.add("Iron")
names.add("Tin")
names.add("Lead")
}
private static void lucas(long b) {
printf("Lucas sequence for%s ratio, where b =%d\n", names[b], b)
print("First 15 elements: ")
long x0 = 1
long x1 = 1
printf("%d,%d", x0, x1)
for (int i = 1; i < 13; ++i) {
long x2 = b * x1 + x0
printf(",%d", x2)
x0 = x1
x1 = x2
}
println()
}
private static void metallic(long b, int dp) {
BigInteger x0 = BigInteger.ONE
BigInteger x1 = BigInteger.ONE
BigInteger x2
BigInteger bb = BigInteger.valueOf(b)
BigDecimal ratio = BigDecimal.ONE.setScale(dp)
int iters = 0
String prev = ratio.toString()
while (true) {
iters++
x2 = bb * x1 + x0
String thiz = (x2.toBigDecimal().setScale(dp) / x1.toBigDecimal().setScale(dp)).toString()
if (prev == thiz) {
String plural = "s"
if (iters == 1) {
plural = ""
}
printf("Value after%d iteration%s:%s\n\n", iters, plural, thiz)
return
}
prev = thiz
x0 = x1
x1 = x2
}
}
static void main(String[] args) {
for (int b = 0; b < 10; ++b) {
lucas(b)
metallic(b, 32)
}
println("Golden ratio, where b = 1:")
metallic(1, 256)
}
} | 574Metallic ratios
| 7groovy
| 4oi5f |
import java.math.BigInteger
fun main() {
for (n in testCases) {
val result = getA004290(n)
println("A004290($n) = $result = $n * ${result / n.toBigInteger()}")
}
}
private val testCases: List<Int>
get() {
val testCases: MutableList<Int> = ArrayList()
for (i in 1..10) {
testCases.add(i)
}
for (i in 95..105) {
testCases.add(i)
}
for (i in intArrayOf(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) {
testCases.add(i)
}
return testCases
}
private fun getA004290(n: Int): BigInteger {
if (n == 1) {
return BigInteger.ONE
}
val arr = Array(n) { IntArray(n) }
for (i in 2 until n) {
arr[0][i] = 0
}
arr[0][0] = 1
arr[0][1] = 1
var m = 0
val ten = BigInteger.TEN
val nBi = n.toBigInteger()
while (true) {
m++
if (arr[m - 1][mod(-ten.pow(m), nBi).toInt()] == 1) {
break
}
arr[m][0] = 1
for (k in 1 until n) {
arr[m][k] = arr[m - 1][k].coerceAtLeast(arr[m - 1][mod(k.toBigInteger() - ten.pow(m), nBi).toInt()])
}
}
var r = ten.pow(m)
var k = mod(-r, nBi)
for (j in m - 1 downTo 1) {
if (arr[j - 1][k.toInt()] == 0) {
r += ten.pow(j)
k = mod(k - ten.pow(j), nBi)
}
}
if (k.compareTo(BigInteger.ONE) == 0) {
r += BigInteger.ONE
}
return r
}
private fun mod(m: BigInteger, n: BigInteger): BigInteger {
var result = m.mod(n)
if (result < BigInteger.ZERO) {
result += n
}
return result
} | 567Minimum positive multiple in base 10 using only 0 and 1
| 11kotlin
| 583ua |
object ModularArithmetic extends App {
private val x = new ModInt(10, 13)
private val y = f(x)
private def f[T](x: Ring[T]) = (x ^ 100) + x + x.one
private trait Ring[T] {
def +(rhs: Ring[T]): Ring[T]
def *(rhs: Ring[T]): Ring[T]
def one: Ring[T]
def ^(p: Int): Ring[T] = {
require(p >= 0, "p must be zero or greater")
var pp = p
var pwr = this.one
while ( {
pp -= 1;
pp
} >= 0) pwr = pwr * this
pwr
}
}
private class ModInt(var value: Int, var modulo: Int) extends Ring[ModInt] {
def +(other: Ring[ModInt]): Ring[ModInt] = {
require(other.isInstanceOf[ModInt], "Cannot add an unknown ring.")
val rhs = other.asInstanceOf[ModInt]
require(modulo == rhs.modulo, "Cannot add rings with different modulus")
new ModInt((value + rhs.value) % modulo, modulo)
}
def *(other: Ring[ModInt]): Ring[ModInt] = {
require(other.isInstanceOf[ModInt], "Cannot multiple an unknown ring.")
val rhs = other.asInstanceOf[ModInt]
require(modulo == rhs.modulo,
"Cannot multiply rings with different modulus")
new ModInt((value * rhs.value) % modulo, modulo)
}
override def one = new ModInt(1, modulo)
override def toString: String = f"ModInt($value%d, $modulo%d)"
}
println("x ^ 100 + x + 1 for x = ModInt(10, 13) is " + y)
} | 564Modular arithmetic
| 16scala
| 7d2r9 |
null | 569Mind boggling card trick
| 11kotlin
| thef0 |
package main
import "fmt"
func contains(is []int, s int) bool {
for _, i := range is {
if s == i {
return true
}
}
return false
}
func mianChowla(n int) []int {
mc := make([]int, n)
mc[0] = 1
is := []int{2}
var sum int
for i := 1; i < n; i++ {
le := len(is)
jloop:
for j := mc[i-1] + 1; ; j++ {
mc[i] = j
for k := 0; k <= i; k++ {
sum = mc[k] + j
if contains(is, sum) {
is = is[0:le]
continue jloop
}
is = append(is, sum)
}
break
}
}
return mc
}
func main() {
mc := mianChowla(100)
fmt.Println("The first 30 terms of the Mian-Chowla sequence are:")
fmt.Println(mc[0:30])
fmt.Println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
fmt.Println(mc[90:100])
} | 571Mian-Chowla sequence
| 0go
| vsi2m |
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
public class MetallicRatios {
private static String[] ratioDescription = new String[] {"Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminum", "Iron", "Tin", "Lead"};
public static void main(String[] args) {
int elements = 15;
for ( int b = 0 ; b < 10 ; b++ ) {
System.out.printf("Lucas sequence for%s ratio, where b =%d:%n", ratioDescription[b], b);
System.out.printf("First%d elements:%s%n", elements, lucasSequence(1, 1, b, elements));
int decimalPlaces = 32;
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to%d decimal places after%s iterations:%s%n", decimalPlaces, ratio[1], ratio[0]);
System.out.printf("%n");
}
int b = 1;
int decimalPlaces = 256;
System.out.printf("%s ratio, where b =%d:%n", ratioDescription[b], b);
BigDecimal[] ratio = lucasSequenceRatio(1, 1, b, decimalPlaces+1);
System.out.printf("Value to%d decimal places after%s iterations:%s%n", decimalPlaces, ratio[1], ratio[0]);
}
private static BigDecimal[] lucasSequenceRatio(int x0, int x1, int b, int digits) {
BigDecimal x0Bi = BigDecimal.valueOf(x0);
BigDecimal x1Bi = BigDecimal.valueOf(x1);
BigDecimal bBi = BigDecimal.valueOf(b);
MathContext mc = new MathContext(digits);
BigDecimal fractionPrior = x1Bi.divide(x0Bi, mc);
int iterations = 0;
while ( true ) {
iterations++;
BigDecimal x = bBi.multiply(x1Bi).add(x0Bi);
BigDecimal fractionCurrent = x.divide(x1Bi, mc);
if ( fractionCurrent.compareTo(fractionPrior) == 0 ) {
break;
}
x0Bi = x1Bi;
x1Bi = x;
fractionPrior = fractionCurrent;
}
return new BigDecimal[] {fractionPrior, BigDecimal.valueOf(iterations)};
}
private static List<BigInteger> lucasSequence(int x0, int x1, int b, int n) {
List<BigInteger> list = new ArrayList<>();
BigInteger x0Bi = BigInteger.valueOf(x0);
BigInteger x1Bi = BigInteger.valueOf(x1);
BigInteger bBi = BigInteger.valueOf(b);
if ( n > 0 ) {
list.add(x0Bi);
}
if ( n > 1 ) {
list.add(x1Bi);
}
while ( n > 2 ) {
BigInteger x = bBi.multiply(x1Bi).add(x0Bi);
list.add(x);
n--;
x0Bi = x1Bi;
x1Bi = x;
}
return list;
}
} | 574Metallic ratios
| 9java
| xl2wy |
function array1D(n, v)
local tbl = {}
for i=1,n do
table.insert(tbl, v)
end
return tbl
end
function array2D(h, w, v)
local tbl = {}
for i=1,h do
table.insert(tbl, array1D(w, v))
end
return tbl
end
function mod(m, n)
m = math.floor(m)
local result = m % n
if result < 0 then
result = result + n
end
return result
end
function getA004290(n)
if n == 1 then
return 1
end
local arr = array2D(n, n, 0)
arr[1][1] = 1
arr[1][2] = 1
local m = 0
while true do
m = m + 1
if arr[m][mod(-10 ^ m, n) + 1] == 1 then
break
end
arr[m + 1][1] = 1
for k = 1, n - 1 do
arr[m + 1][k + 1] = math.max(arr[m][k + 1], arr[m][mod(k - 10 ^ m, n) + 1])
end
end
local r = 10 ^ m
local k = mod(-r, n)
for j = m - 1, 1, -1 do
if arr[j][k + 1] == 0 then
r = r + 10 ^ j
k = mod(k - 10 ^ j, n)
end
end
if k == 1 then
r = r + 1
end
return r
end
function test(cases)
for _,n in ipairs(cases) do
local result = getA004290(n)
print(string.format("A004290(%d) =%s =%d *%d", n, math.floor(result), n, math.floor(result / n)))
end
end
test({1, 2, 3, 4, 5, 6, 7, 8, 9})
test({95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105})
test({297, 576, 594, 891, 909, 999}) | 567Minimum positive multiple in base 10 using only 0 and 1
| 1lua
| 4o65c |
multiplication_table <- function(n=12)
{
one_to_n <- 1:n
x <- matrix(one_to_n)%*% t(one_to_n)
x[lower.tri(x)] <- 0
rownames(x) <- colnames(x) <- one_to_n
print(as.table(x), zero.print="")
invisible(x)
}
multiplication_table() | 560Multiplication tables
| 13r
| e9pad |
import Data.Set (Set, fromList, insert, member)
mianChowlas :: Int -> [Int]
mianChowlas =
reverse . snd . (iterate nextMC (fromList [2], [1]) !!) . subtract 1
nextMC :: (Set Int, [Int]) -> (Set Int, [Int])
nextMC (sumSet, mcs@(n:_)) =
(foldr insert sumSet ((2 * m): fmap (m +) mcs), m: mcs)
where
valid x = not $ any (flip member sumSet . (x +)) mcs
m = until valid succ n
main :: IO ()
main =
(putStrLn . unlines)
[ "First 30 terms of the Mian-Chowla series:"
, show (mianChowlas 30)
, []
, "Terms 91 to 100 of the Mian-Chowla series:"
, show $ drop 90 (mianChowlas 100)
] | 571Mian-Chowla sequence
| 8haskell
| e9vai |
package main
import "fmt"
type person struct{
name string
age int
}
func copy(p person) person {
return person{p.name, p.age}
}
func main() {
p := person{"Dave", 40}
fmt.Println(p)
q := copy(p)
fmt.Println(q)
} | 572Metaprogramming
| 0go
| 4od52 |
macro dowhile(condition, block)
quote
while true
$(esc(block))
if!$(esc(condition))
break
end
end
end
end
macro dountil(condition, block)
quote
while true
$(esc(block))
if $(esc(condition))
break
end
end
end
end
using Primes
arr = [7, 31]
@dowhile (!isprime(arr[1]) &&!isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.")
@dountil (isprime(arr[1]) || isprime(arr[2])) begin
println(arr)
arr .+= 1
end
println("Done.") | 572Metaprogramming
| 8haskell
| q25x9 |
import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
var x1 = 1L
print("$x0, $x1")
for (i in 1..13) {
val x2 = b * x1 + x0
print(", $x2")
x0 = x1
x1 = x2
}
println()
}
fun metallic(b: Long, dp:Int) {
var x0 = BigInteger.ONE
var x1 = BigInteger.ONE
var x2: BigInteger
val bb = BigInteger.valueOf(b)
val ratio = BigDecimal.ONE.setScale(dp)
var iters = 0
var prev = ratio.toString()
while (true) {
iters++
x2 = bb * x1 + x0
val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()
if (prev == thiz) {
var plural = "s"
if (iters == 1) {
plural = ""
}
println("Value after $iters iteration$plural: $thiz\n")
return
}
prev = thiz
x0 = x1
x1 = x2
}
}
fun main() {
for (b in 0L until 10L) {
lucas(b)
metallic(b, 32)
}
println("Golden ration, where b = 1:")
metallic(1, 256)
} | 574Metallic ratios
| 11kotlin
| p6yb6 |
package main
import (
"bufio"
"fmt"
"math"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type cell struct {
isMine bool
display byte | 568Minesweeper game
| 0go
| b32kh |
package main
import (
"log"
"os"
"sync"
"time"
) | 570Metered concurrency
| 0go
| 58ful |
precedencegroup ExponentiationGroup {
higherThan: MultiplicationPrecedence
}
infix operator **: ExponentiationGroup
protocol Ring {
associatedtype RingType: Numeric
var one: Self { get }
static func +(_ lhs: Self, _ rhs: Self) -> Self
static func *(_ lhs: Self, _ rhs: Self) -> Self
static func **(_ lhs: Self, _ rhs: Int) -> Self
}
extension Ring {
static func **(_ lhs: Self, _ rhs: Int) -> Self {
var ret = lhs.one
for _ in stride(from: rhs, to: 0, by: -1) {
ret = ret * lhs
}
return ret
}
}
struct ModInt: Ring {
typealias RingType = Int
var value: Int
var modulo: Int
var one: ModInt { ModInt(1, modulo: modulo) }
init(_ value: Int, modulo: Int) {
self.value = value
self.modulo = modulo
}
static func +(lhs: ModInt, rhs: ModInt) -> ModInt {
precondition(lhs.modulo == rhs.modulo)
return ModInt((lhs.value + rhs.value)% lhs.modulo, modulo: lhs.modulo)
}
static func *(lhs: ModInt, rhs: ModInt) -> ModInt {
precondition(lhs.modulo == rhs.modulo)
return ModInt((lhs.value * rhs.value)% lhs.modulo, modulo: lhs.modulo)
}
}
func f<T: Ring>(_ x: T) -> T { (x ** 100) + x + x.one }
let x = ModInt(10, modulo: 13)
let y = f(x)
print("x ^ 100 + x + 1 for x = ModInt(10, 13) is \(y)") | 564Modular arithmetic
| 17swift
| u0yvg |
sub trick {
my(@deck) = @_;
my $result .= sprintf "%-28s @deck\n", 'Starting deck:';
my(@discard, @red, @black);
deal(\@deck, \@discard, \@red, \@black);
$result .= sprintf "%-28s @red\n", 'Red pile:';
$result .= sprintf "%-28s @black\n", 'Black pile:';
my $n = int rand(+@red < +@black ? +@red : +@black);
swap(\@red, \@black, $n);
$result .= sprintf "Red pile after%2d swapped: @red\n", $n;
$result .= sprintf "Black pile after%2d swapped: @black\n", $n;
$result .= sprintf "Red in Red, Black in Black: %d =%d\n", (scalar grep {/R/} @red), scalar grep {/B/} @black;
return "$result\n";
}
sub deal {
my($c, $d, $r, $b) = @_;
while (@$c) {
my $top = shift @$c;
if ($top eq 'R') { push @$r, shift @$c }
else { push @$b, shift @$c }
push @$d, $top;
}
}
sub swap {
my($r, $b, $n) = @_;
push @$r, splice @$b, 0, $n;
push @$b, splice @$r, 0, $n;
}
@deck = split '', 'RB' x 26;
print trick(@deck);
@deck = split '', 'RRBB' x 13;
print trick(@deck);
@deck = sort @deck;
print trick(@deck);
@deck = sort { -1 + 2*int(rand 2) } @deck;
print trick(@deck); | 569Mind boggling card trick
| 2perl
| kzchc |
import java.util.Arrays;
public class MianChowlaSequence {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println("First 30 terms of the MianChowla sequence.");
mianChowla(1, 30);
System.out.println("Terms 91 through 100 of the MianChowla sequence.");
mianChowla(91, 100);
long end = System.currentTimeMillis();
System.out.printf("Elapsed =%d ms%n", (end-start));
}
private static void mianChowla(int minIndex, int maxIndex) {
int [] sums = new int[1];
int [] chowla = new int[maxIndex+1];
sums[0] = 2;
chowla[0] = 0;
chowla[1] = 1;
if ( minIndex == 1 ) {
System.out.printf("%d ", 1);
}
int chowlaLength = 1;
for ( int n = 2 ; n <= maxIndex ; n++ ) { | 571Mian-Chowla sequence
| 9java
| htyjm |
package main
import (
"fmt"
"time"
)
func main() {
var bpm = 72.0 | 573Metronome
| 0go
| y1e64 |
class CountingSemaphore {
private int count = 0
private final int max
CountingSemaphore(int max) { this.max = max }
synchronized int acquire() {
while (count >= max) { wait() }
++count
}
synchronized int release() {
if (count) { count--; notifyAll() }
count
}
synchronized int getCount() { count }
} | 570Metered concurrency
| 7groovy
| cw89i |
import Control.Concurrent
( newQSem,
signalQSem,
waitQSem,
threadDelay,
forkIO,
newEmptyMVar,
putMVar,
takeMVar,
QSem,
MVar )
import Control.Monad ( replicateM_ )
worker :: QSem -> MVar String -> Int -> IO ()
worker q m n = do
waitQSem q
putMVar m $ "Worker " <> show n <> " has acquired the lock."
threadDelay 2000000
signalQSem q
putMVar m $ "Worker " <> show n <> " has released the lock."
main :: IO ()
main = do
q <- newQSem 3
m <- newEmptyMVar
let workers = 5
prints = 2 * workers
mapM_ (forkIO . worker q m) [1 .. workers]
replicateM_ prints $ takeMVar m >>= putStrLn | 570Metered concurrency
| 8haskell
| xl4w4 |
(() => {
'use strict'; | 571Mian-Chowla sequence
| 10javascript
| am210 |
null | 572Metaprogramming
| 11kotlin
| 7dzr4 |
use strict;
use warnings;
use feature qw(say state);
use Math::AnyNum qw<:overload as_dec>;
sub gen_lucas {
my $b = shift;
my $i = 0;
return sub {
state @seq = (state $v1 = 1, state $v2 = 1);
($v2, $v1) = ($v1, $v2 + $b*$v1) and push(@seq, $v1) unless defined $seq[$i+1];
return $seq[$i++];
}
}
sub metallic {
my $lucas = shift;
my $places = shift || 32;
my $n = my $last = 0;
my @seq = $lucas->();
while (1) {
push @seq, $lucas->();
my $this = as_dec( $seq[-1]/$seq[-2], $places+1 );
last if $this eq $last;
$last = $this;
$n++;
}
$last, $n
}
my @name = <Platinum Golden Silver Bronze Copper Nickel Aluminum Iron Tin Lead>;
for my $b (0..$
my $lucas = gen_lucas($b);
printf "\n'Lucas' sequence for $name[$b] ratio, where b = $b:\nFirst 15 elements: " . join ', ', map { $lucas->() } 1..15;
printf "Approximated value%s reached after%d iterations\n", metallic(gen_lucas($b));
}
printf "\nGolden ratio to 256 decimal places%s reached after%d iterations", metallic(gen_lucas(1),256); | 574Metallic ratios
| 2perl
| y1a6u |
module MineSweeper
( Board
, Cell(..)
, CellState(..)
, Pos
, pos
, coveredLens
, coveredFlaggedLens
, coveredMinedLens
, xCoordLens
, yCoordLens
, emptyBoard
, groupedByRows
, displayCell
, isLoss
, isWin
, exposeMines
, openCell
, flagCell
, mineBoard
, totalRows
, totalCols )
where
import Control.Lens ((%~), (&), (.~), (^.), (^?), Lens', Traversal', _1, _2,
anyOf, filtered, folded, lengthOf, makeLenses, makePrisms,
preview, to, view)
import Data.List (find, groupBy, nub, delete, sortBy)
import Data.Maybe (isJust)
import System.Random (getStdGen, getStdRandom, randomR, randomRs)
type Pos = (Int, Int)
type Board = [Cell]
data CellState = Covered { _mined :: Bool, _flagged :: Bool }
| UnCovered { _mined :: Bool }
deriving (Show, Eq)
data Cell = Cell
{ _pos :: Pos
, _state :: CellState
, _cellId :: Int
, _adjacentMines :: Int }
deriving (Show, Eq)
makePrisms ''CellState
makeLenses ''CellState
makeLenses ''Cell
coveredLens :: Traversal' Cell (Bool, Bool)
coveredLens = state . _Covered
coveredMinedLens, coveredFlaggedLens, unCoveredLens :: Traversal' Cell Bool
coveredMinedLens = coveredLens . _1
coveredFlaggedLens = coveredLens . _2
unCoveredLens = state . _UnCovered
xCoordLens, yCoordLens :: Lens' Cell Int
xCoordLens = pos . _1
yCoordLens = pos . _2
totalRows, totalCols :: Int
totalRows = 4
totalCols = 6
emptyBoard :: Board
emptyBoard = (\(n, p) -> Cell { _pos = p
, _state = Covered False False
, _adjacentMines = 0
, _cellId = n }) <$> zip [1..] positions
where
positions = (,) <$> [1..totalCols] <*> [1..totalRows]
updateCell :: Cell -> Board -> Board
updateCell cell = fmap (\c -> if cell ^. cellId == c ^. cellId then cell else c)
updateBoard :: Board -> [Cell] -> Board
updateBoard = foldr updateCell
okToOpen :: [Cell] -> [Cell]
okToOpen = filter (\c -> c ^? coveredLens == Just (False, False))
openUnMined :: Cell -> Cell
openUnMined = state .~ UnCovered False
openCell :: Pos -> Board -> Board
openCell p b = f $ find (\c -> c ^. pos == p) b
where
f (Just c)
| c ^? coveredFlaggedLens == Just True = b
| c ^? coveredMinedLens == Just True = updateCell
(c & state .~ UnCovered True)
b
| isCovered c = if c ^. adjacentMines == 0 && not (isFirstMove b)
then updateCell (openUnMined c) $ expandEmptyCells b c
else updateCell (openUnMined c) b
| otherwise = b
f Nothing = b
isCovered = isJust . preview coveredLens
expandEmptyCells :: Board -> Cell -> Board
expandEmptyCells board cell
| null openedCells = board
| otherwise = foldr (flip expandEmptyCells) updatedBoard (zeroAdjacent openedCells)
where
findMore _ [] = []
findMore exclude (c: xs)
| c `elem` exclude = findMore exclude xs
| c ^. adjacentMines == 0 = c: adjacent c <>
findMore (c: exclude <> adjacent c) xs
| otherwise = c: findMore (c: exclude) xs
adjacent = okToOpen . flip adjacentCells board
openedCells = openUnMined <$> nub (findMore [cell] (adjacent cell))
zeroAdjacent = filter (view (adjacentMines . to (== 0)))
updatedBoard = updateBoard board openedCells
flagCell :: Pos -> Board -> Board
flagCell p board = case find ((== p) . view pos) board of
Just c -> updateCell (c & state . flagged %~ not) board
Nothing -> board
adjacentCells :: Cell -> Board -> [Cell]
adjacentCells Cell {_pos = c@(x1, y1)} = filter (\c -> c ^. pos `elem` positions)
where
f n = [pred n, n, succ n]
positions = delete c $ [(x, y) | x <- f x1, x > 0, y <- f y1, y > 0]
isLoss, isWin, allUnMinedOpen, allMinesFlagged, isFirstMove :: Board -> Bool
isLoss = anyOf (traverse . unCoveredLens) (== True)
isWin b = allUnMinedOpen b || allMinesFlagged b
allUnMinedOpen = (== 0) . lengthOf (traverse . coveredMinedLens . filtered (== False))
allMinesFlagged b = minedCount b == flaggedMineCount b
where
minedCount = lengthOf (traverse . coveredMinedLens . filtered (== True))
flaggedMineCount = lengthOf (traverse . coveredLens . filtered (== (True, True)))
isFirstMove = (== totalCols * totalRows) . lengthOf (folded . coveredFlaggedLens . filtered (== False))
groupedByRows :: Board -> [Board]
groupedByRows = groupBy (\c1 c2 -> yAxis c1 == yAxis c2)
. sortBy (\c1 c2 -> yAxis c1 `compare` yAxis c2)
where
yAxis = view yCoordLens
displayCell :: Cell -> String
displayCell c
| c ^? unCoveredLens == Just True = "X"
| c ^? coveredFlaggedLens == Just True = "?"
| c ^? (unCoveredLens . to not) == Just True =
if c ^. adjacentMines > 0 then show $ c ^. adjacentMines else ""
| otherwise = "."
exposeMines :: Board -> Board
exposeMines = fmap (\c -> c & state . filtered (\s -> s ^? _Covered . _1 == Just True) .~ UnCovered True)
updateMineCount :: Board -> Board
updateMineCount b = go b
where
go [] = []
go (x: xs) = (x & adjacentMines .~ totalAdjacentMines b): go xs
where
totalAdjacentMines =
foldr (\c acc -> if c ^. (state . mined) then succ acc else acc) 0 . adjacentCells x
mineBoard :: Pos -> Board -> IO Board
mineBoard p board = do
totalMines <- randomMinedCount
minedBoard totalMines >>= \mb -> pure $ updateMineCount mb
where
mines n = take n <$> randomCellIds
minedBoard n = (\m ->
fmap (\c -> if c ^. cellId `elem` m then c & state . mined .~ True else c)
board) . filter (\c -> openedCell ^. cellId /= c)
<$> mines n
openedCell = head $ filter (\c -> c ^. pos == p) board
randomCellIds :: IO [Int]
randomCellIds = randomRs (1, totalCols * totalRows) <$> getStdGen
randomMinedCount :: IO Int
randomMinedCount = getStdRandom $ randomR (minMinedCells, maxMinedCells)
where
maxMinedCells = floor $ realToFrac (totalCols * totalRows) * 0.2
minMinedCells = floor $ realToFrac (totalCols * totalRows) * 0.1 | 568Minesweeper game
| 8haskell
| d7an4 |
import Control.Concurrent
import Control.Concurrent.MVar
import System.Process (runCommand)
data Beep = Stop | Hi | Low
type Pattern = [Beep]
type BeatsPerMinute = Int
minute = 60000000
pattern4_4 = [Hi, Low, Low, Low]
pattern2_4 = [Hi, Low]
pattern3_4 = [Hi, Low, Low]
pattern6_8 = [Hi, Low, Low, Low, Low, Low]
beep Stop = return ()
beep Hi = putChar 'H' >> runCommand "aplay hi.wav &> /dev/null" >> return ()
beep Low = putChar 'L' >> runCommand "aplay low.wav &> /dev/null" >> return ()
tick :: MVar Pattern -> BeatsPerMinute -> IO ()
tick b i = do
t <- readMVar b
case t of
[Stop] -> return ()
x -> do
mapM_ (\v -> forkIO (beep v) >> threadDelay (minute `div` i)) t
tick b i
metronome :: Pattern -> BeatsPerMinute -> IO ()
metronome p i = do
putStrLn "Press any key to stop the metronome."
b <- newMVar p
_ <- forkIO $ tick b i
_ <- getChar
putMVar b [Stop] | 573Metronome
| 8haskell
| ht3ju |
import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n
reds = [Red] * (n
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.append(pack.pop())
discard.append(top)
print('(Discards:', ' '.join(d[0] for d in discard), ')\n')
max_swaps = min(len(black_stack), len(red_stack))
swap_count = random.randint(0, max_swaps)
print('Swapping', swap_count)
def random_partition(stack, count):
sample = random.sample(stack, count)
rest = stack[::]
for card in sample:
rest.remove(card)
return rest, sample
black_stack, black_swap = random_partition(black_stack, swap_count)
red_stack, red_swap = random_partition(red_stack, swap_count)
black_stack += red_swap
red_stack += black_swap
if black_stack.count(Black) == red_stack.count(Red):
print('Yeha! The mathematicians assertion is correct.')
else:
print('Whoops - The mathematicians (or my card manipulations) are flakey') | 569Mind boggling card trick
| 3python
| b3lkr |
class "foo" : inherits "bar"
{
} | 572Metaprogramming
| 1lua
| jf371 |
typedef struct { unsigned char r, g, b; } rgb_t;
typedef struct {
int w, h;
rgb_t **pix;
} image_t, *image;
typedef struct {
int r[256], g[256], b[256];
int n;
} color_histo_t;
int write_ppm(image im, char *fn)
{
FILE *fp = fopen(fn, );
if (!fp) return 0;
fprintf(fp, , im->w, im->h);
fwrite(im->pix[0], 1, sizeof(rgb_t) * im->w * im->h, fp);
fclose(fp);
return 1;
}
image img_new(int w, int h)
{
int i;
image im = malloc(sizeof(image_t) + h * sizeof(rgb_t*)
+ sizeof(rgb_t) * w * h);
im->w = w; im->h = h;
im->pix = (rgb_t**)(im + 1);
for (im->pix[0] = (rgb_t*)(im->pix + h), i = 1; i < h; i++)
im->pix[i] = im->pix[i - 1] + w;
return im;
}
int read_num(FILE *f)
{
int n;
while (!fscanf(f, , &n)) {
if ((n = fgetc(f)) == '
while ((n = fgetc(f)) != '\n')
if (n == EOF) break;
if (n == '\n') continue;
} else return 0;
}
return n;
}
image read_ppm(char *fn)
{
FILE *fp = fopen(fn, );
int w, h, maxval;
image im = 0;
if (!fp) return 0;
if (fgetc(fp) != 'P' || fgetc(fp) != '6' || !isspace(fgetc(fp)))
goto bail;
w = read_num(fp);
h = read_num(fp);
maxval = read_num(fp);
if (!w || !h || !maxval) goto bail;
im = img_new(w, h);
fread(im->pix[0], 1, sizeof(rgb_t) * w * h, fp);
bail:
if (fp) fclose(fp);
return im;
}
void del_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]--;
h->g[pix->g]--;
h->b[pix->b]--;
h->n--;
}
}
void add_pixels(image im, int row, int col, int size, color_histo_t *h)
{
int i;
rgb_t *pix;
if (col < 0 || col >= im->w) return;
for (i = row - size; i <= row + size && i < im->h; i++) {
if (i < 0) continue;
pix = im->pix[i] + col;
h->r[pix->r]++;
h->g[pix->g]++;
h->b[pix->b]++;
h->n++;
}
}
void init_histo(image im, int row, int size, color_histo_t*h)
{
int j;
memset(h, 0, sizeof(color_histo_t));
for (j = 0; j < size && j < im->w; j++)
add_pixels(im, row, j, size, h);
}
int median(const int *x, int n)
{
int i;
for (n /= 2, i = 0; i < 256 && (n -= x[i]) > 0; i++);
return i;
}
void median_color(rgb_t *pix, const color_histo_t *h)
{
pix->r = median(h->r, h->n);
pix->g = median(h->g, h->n);
pix->b = median(h->b, h->n);
}
image median_filter(image in, int size)
{
int row, col;
image out = img_new(in->w, in->h);
color_histo_t h;
for (row = 0; row < in->h; row ++) {
for (col = 0; col < in->w; col++) {
if (!col) init_histo(in, row, size, &h);
else {
del_pixels(in, row, col - size, size, &h);
add_pixels(in, row, col + size, size, &h);
}
median_color(out->pix[row] + col, &h);
}
}
return out;
}
int main(int c, char **v)
{
int size;
image in, out;
if (c <= 3) {
printf(, v[0]);
return 0;
}
size = atoi(v[1]);
printf(, size);
if (size < 0) size = 1;
in = read_ppm(v[2]);
out = median_filter(in, size);
write_ppm(out, v[3]);
free(in);
free(out);
return 0;
} | 575Median filter
| 5c
| 2qqlo |
use strict;
use warnings;
use Math::AnyNum qw(:overload as_bin digits2num);
for my $x (1..10, 95..105, 297, 576, 594, 891, 909, 999) {
my $y;
if ($x =~ /^9+$/) { $y = digits2num([(1) x (9 * length $x)],2) }
else { while (1) { last unless as_bin(++$y) % $x } }
printf "%4d:%28s %s\n", $x, as_bin($y), as_bin($y)/$x;
} | 567Minimum positive multiple in base 10 using only 0 and 1
| 2perl
| o4p8x |
use bigint;
sub expmod {
my($a, $b, $n) = @_;
my $c = 1;
do {
($c *= $a) %= $n if $b % 2;
($a *= $a) %= $n;
} while ($b = int $b/2);
$c;
}
my $a = 2988348162058574136915891421498819466320163312926952423791023078876139;
my $b = 2351399303373464486466122544523690094744975233415544072992656881240319;
my $m = 10 ** 40;
print expmod($a, $b, $m), "\n";
print $a->bmodpow($b, $m), "\n"; | 566Modular exponentiation
| 2perl
| 7dcrh |
public class CountingSemaphore{
private int lockCount = 0;
private int maxCount;
CountingSemaphore(int Max){
maxCount = Max;
}
public synchronized void acquire() throws InterruptedException{
while( lockCount >= maxCount){
wait();
}
lockCount++;
}
public synchronized void release(){
if (lockCount > 0)
{
lockCount--;
notifyAll();
}
}
public synchronized int getCount(){
return lockCount;
}
}
public class Worker extends Thread{
private CountingSemaphore lock;
private int id;
Worker(CountingSemaphore coordinator, int num){
lock = coordinator;
id = num;
}
Worker(){
}
public void run(){
try{
lock.acquire();
System.out.println("Worker " + id + " has acquired the lock.");
sleep(2000);
}
catch (InterruptedException e){
}
finally{
lock.release();
}
}
public static void main(String[] args){
CountingSemaphore lock = new CountingSemaphore(3);
Worker crew[];
crew = new Worker[5];
for (int i = 0; i < 5; i++){
crew[i] = new Worker(lock, i);
crew[i].start();
}
}
} | 570Metered concurrency
| 9java
| b3ck3 |
magictrick<-function(){
deck=c(rep("B",26),rep("R",26))
deck=sample(deck,52)
blackpile=character(0)
redpile=character(0)
discardpile=character(0)
while(length(deck)>0){
if(deck[1]=="B"){
blackpile=c(blackpile,deck[2])
deck=deck[-2]
}else{
redpile=c(redpile,deck[2])
deck=deck[-2]
}
discardpile=c(discardpile,deck[1])
deck=deck[-1]
}
cat("After the deal the state of the piles is:","\n",
"Black pile:",blackpile,"\n","Red pile:",redpile,"\n",
"Discard pile:",discardpile,"\n","\n")
X=sample(1:min(length(redpile),length(blackpile)),1)
if(X==1){s=" is"}else{s="s are"}
cat(X," card",s," being swapped.","\n","\n",sep="")
redindex=sample(1:length(redpile),X)
blackindex=sample(1:length(blackpile),X)
redbunch=redpile[redindex]
redpile=redpile[-redindex]
blackbunch=blackpile[blackindex]
blackpile=blackpile[-blackindex]
redpile=c(redpile,blackbunch)
blackpile=c(blackpile,redbunch)
cat("After the swap the state of the piles is:","\n",
"Black pile:",blackpile,"\n","Red pile:",redpile,"\n","\n")
cat("There are ", length(which(blackpile=="B")), " black cards in the black pile.","\n",
"There are ", length(which(redpile=="R")), " red cards in the red pile.","\n",sep="")
if(length(which(blackpile=="B"))==length(which(redpile=="R"))){
cat("The assertion is true!")
}
} | 569Mind boggling card trick
| 13r
| 7dyry |
null | 571Mian-Chowla sequence
| 11kotlin
| 4of57 |
from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext().prec = prec
last = 0
for i,x in zip(count(), to_decimal(b)):
if x == last:
print(f'after {i} iterations:\n\t{x}')
break
last = x
for b in range(4):
coefs = [n for _,n in islice(metallic_ratio(b), 15)]
print(f'\nb = {b}: {coefs}')
stable(b, 32)
print(f'\nb = 1 with 256 digits:')
stable(1, 256) | 574Metallic ratios
| 3python
| maeyh |
--------------------------------- START of Main.java --------------------------------- | 568Minesweeper game
| 9java
| svjq0 |
class Metronome{
double bpm;
int measure, counter;
public Metronome(double bpm, int measure){
this.bpm = bpm;
this.measure = measure;
}
public void start(){
while(true){
try {
Thread.sleep((long)(1000*(60.0/bpm)));
}catch(InterruptedException e) {
e.printStackTrace();
}
counter++;
if (counter%measure==0){
System.out.println("TICK");
}else{
System.out.println("TOCK");
}
}
}
}
public class test {
public static void main(String[] args) {
Metronome metronome1 = new Metronome(120,4);
metronome1.start();
}
} | 573Metronome
| 9java
| 58iuf |
null | 570Metered concurrency
| 11kotlin
| rn3go |
bool miller_rabin_test(mpz_t n, int j); | 576Miller–Rabin primality test
| 5c
| p63by |
package main | 575Median filter
| 0go
| q22xz |
def getA004290(n):
if n < 2:
return 1
arr = [[0 for _ in range(n)] for _ in range(n)]
arr[0][0] = 1
arr[0][1] = 1
m = 0
while True:
m += 1
if arr[m - 1][-10 ** m% n] == 1:
break
arr[m][0] = 1
for k in range(1, n):
arr[m][k] = max([arr[m - 1][k], arr[m - 1][k - 10 ** m% n]])
r = 10 ** m
k = -r% n
for j in range((m - 1), 0, -1):
if arr[j - 1][k] == 0:
r = r + 10 ** j
k = (k - 10 ** j)% n
if k == 1:
r += 1
return r
for n in [i for i in range(1, 11)] + \
[i for i in range(95, 106)] + \
[297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878]:
result = getA004290(n)
print(f) | 567Minimum positive multiple in base 10 using only 0 and 1
| 3python
| ig1of |
<?php
$a = '2988348162058574136915891421498819466320163312926952423791023078876139';
$b = '2351399303373464486466122544523690094744975233415544072992656881240319';
$m = '1' . str_repeat('0', 40);
echo bcpowmod($a, $b, $m), ; | 566Modular exponentiation
| 12php
| fjxdh |
null | 573Metronome
| 11kotlin
| cwq98 |
def multiplication_table(n)
puts + ( * n) % [*1..n]
puts + * n
1.upto(n) do |x|
print % x
1.upto(x-1) {|y| print }
x.upto(n) {|y| print % (x*y)}
puts
end
end
multiplication_table 12 | 560Multiplication tables
| 14ruby
| 85q01 |
use strict;
use warnings;
use feature 'say';
sub generate_mc {
my($max) = @_;
my $index = 0;
my $test = 1;
my %sums = (2 => 1);
my @mc = 1;
while ($test++) {
my %these = %sums;
map { next if ++$these{$_ + $test} > 1 } @mc[0..$index], $test;
%sums = %these;
$index++;
return @mc if (push @mc, $test) > $max-1;
}
}
my @mian_chowla = generate_mc(100);
say "First 30 terms in the MianChowla sequence:\n", join(' ', @mian_chowla[ 0..29]),
"\nTerms 91 through 100:\n", join(' ', @mian_chowla[90..99]); | 571Mian-Chowla sequence
| 2perl
| igho3 |
package main
import "fmt"
type rs232p9 uint16
const (
CD9 rs232p9 = 1 << iota | 577Memory layout of a data structure
| 0go
| cwa9g |
a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10 ** 40
print(pow(a, b, m)) | 566Modular exponentiation
| 3python
| jfl7p |
deck = ([:black, :red] * 26 ).shuffle
black_pile, red_pile, discard = [], [], []
until deck.empty? do
discard << deck.pop
discard.last == :black? black_pile << deck.pop: red_pile << deck.pop
end
x = rand( [black_pile.size, red_pile.size].min )
red_bunch = x.times.map{ red_pile.delete_at( rand( red_pile.size )) }
black_bunch = x.times.map{ black_pile.delete_at( rand( black_pile.size )) }
black_pile += red_bunch
red_pile += black_bunch
puts | 569Mind boggling card trick
| 14ruby
| 1yvpw |
package UnicodeEllipsis;
use Filter::Simple;
FILTER_ONLY code => sub { s//../g }; | 572Metaprogramming
| 2perl
| fjbd7 |
(ns test-p.core
(:require [clojure.math.numeric-tower :as math])
(:require [clojure.set :as set]))
(def WITNESSLOOP "witness")
(def COMPOSITE "composite")
(defn m* [p q m]
" Computes (p*q) mod m "
(mod (*' p q) m))
(defn power
"modular exponentiation (i.e. b^e mod m"
[b e m]
(loop [b b, e e, x 1]
(if (zero? e)
x
(if (even? e) (recur (m* b b m) (quot e 2) x)
(recur (m* b b m) (quot e 2) (m* b x m))))))
(defn rand-num [n]
" random number between 2 and n-2 "
(bigint (math/floor (+' 2 (*' (- n 4) (rand))))))
(defn unique-random-numbers [n k]
" k unique random numbers between 2 and n-2 "
(loop [a-set #{}]
(cond
(>= (count a-set) k) a-set
:else (recur (conj a-set (rand-num n))))))
(defn find-d-s [n]
" write n 1 as 2sd with d odd "
(loop [d (dec n), s 0]
(if (odd? d)
[d s]
(recur (quot d 2) (inc s)))))
(defn random-test
([n] (random-test n (min 1000 (bigint (/ n 2)))))
([n k]
" Random version of primality test"
(let [[d s] (find-d-s n)
single-test (fn [a s]
(let [z (power a d n)]
(if (some #{z} [1 (dec n)])
WITNESSLOOP
(loop [x (power z 2 n), r s]
(cond
(= x 1) COMPOSITE
(= x (dec n)) WITNESSLOOP
(= r 0) COMPOSITE
:else (recur (power x 2 n) (dec r)))))))]
(not-any? #(= COMPOSITE (single-test % s)) (unique-random-numbers n k)))))
(println "Primes beteen 900-1000:")
(doseq [q (range 900 1000)
:when (random-test q)]
(print " " q))
(println)
(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909489 (random-test 4547337172376300111955330758342147474062293202868155909489))
(println "Is Prime?" 4547337172376300111955330758342147474062293202868155909393 (random-test 4547337172376300111955330758342147474062293202868155909393))
(println "Is Prime?" 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
(random-test 643808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153))
(println "Is Prime?" 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153
(random-test 743808006803554439230129854961492699151386107534013432918073439524138264842370630061369715394739134090922937332590384720397133335969549256322620979036686633213903952966175107096769180017646161851573147596390153)) | 576Miller–Rabin primality test
| 6clojure
| xlcwk |
null | 577Memory layout of a data structure
| 11kotlin
| vsx21 |
require('bigdecimal')
require('bigdecimal/util')
def lucas(b)
Enumerator.new do |yielder|
xn2 = 1; yielder.yield(xn2)
xn1 = 1; yielder.yield(xn1)
loop { xn2, xn1 = xn1, b * xn1 + xn2; yielder.yield(xn1) }
end
end
def metallic_ratio(b, precision)
xn2 = xn1 = prev = this = 0
lucas(b).each.with_index do |xn, inx|
case inx
when 0
xn2 = BigDecimal(xn)
when 1
xn1 = BigDecimal(xn)
prev = xn1.div(xn2, 2 * precision).round(precision)
else
xn2, xn1 = xn1, BigDecimal(xn)
this = xn1.div(xn2, 2 * precision).round(precision)
return Struct.new(:ratio, :terms).new(prev, inx - 1) if prev == this
prev = this
end
end
end
NAMES = [ 'Platinum', 'Golden', 'Silver', 'Bronze', 'Copper',
'Nickel', 'Aluminum', 'Iron', 'Tin', 'Lead' ]
puts
puts('Lucas Sequences...')
puts('%1s %s' % ['b', 'sequence'])
(0..9).each do |b|
puts('%1d %s' % [b, lucas(b).first(15)])
end
puts
puts('Metallic Ratios to 32 places...')
puts('%-9s%1s%3s %s' % ['name', 'b', 'n', 'ratio'])
(0..9).each do |b|
rn = metallic_ratio(b, 32)
puts('%-9s%1d%3d %s' % [NAMES[b], b, rn.terms, rn.ratio.to_s('F')])
end
puts
puts('Golden Ratio to 256 places...')
puts('%-9s%1s%3s %s' % ['name', 'b', 'n', 'ratio'])
gold_rn = metallic_ratio(1, 256)
puts('%-9s%1d%3d %s' % [NAMES[1], 1, gold_rn.terms, gold_rn.ratio.to_s('F')]) | 574Metallic ratios
| 14ruby
| cwx9k |
null | 575Median filter
| 11kotlin
| 8550q |
without js -- (tasks)
sequence sems = {}
constant COUNTER = 1, QUEUE = 2
function semaphore(integer n)
if n>0 then
sems = append(sems,{n,{}})
return length(sems)
else
return 0
end if
end function
procedure acquire(integer id)
if sems[id][COUNTER]=0 then
task_suspend(task_self())
sems[id][QUEUE] &= task_self()
task_yield()
end if
sems[id][COUNTER] -= 1
end procedure
procedure release(integer id)
sems[id][COUNTER] += 1
if length(sems[id][QUEUE])>0 then
task_schedule(sems[id][QUEUE][1],1)
sems[id][QUEUE] = sems[id][QUEUE][2..$]
end if
end procedure
function count(integer id)
return sems[id][COUNTER]
end function
procedure delay(atom delaytime)
atom t = time()
while time()-t<delaytime do
task_yield()
end while
end procedure
integer sem = semaphore(4)
procedure worker()
acquire(sem)
printf(1,"- Task%d acquired semaphore.\n",task_self())
delay(2)
release(sem)
printf(1,"+ Task%d released semaphore.\n",task_self())
end procedure
for i=1 to 10 do
integer task = task_create(routine_id("worker"),{})
task_schedule(task,1)
task_yield()
end for
integer sc = 0
atom t0 = time()+1
while length(task_list())>1 do
task_yield()
integer scnew = count(sem)
if scnew!=sc
or time()>t0 then
sc = scnew
printf(1,"Semaphore count now%d\n",{sc})
t0 = time()+2
end if
end while
?"done"
{} = wait_key() | 570Metered concurrency
| 2perl
| d7pnw |
const LIMIT: i32 = 12;
fn main() {
for i in 1..LIMIT+1 {
print!("{:3}{}", i, if LIMIT - i == 0 {'\n'} else {' '})
}
for i in 0..LIMIT+1 {
print!("{}", if LIMIT - i == 0 {"+\n"} else {"----"});
}
for i in 1..LIMIT+1 {
for j in 1..LIMIT+1 {
if j < i {
print!(" ")
} else {
print!("{:3} ", j * i)
}
}
println!("| {}", i);
}
} | 560Multiplication tables
| 15rust
| o4s83 |
extern crate rand; | 569Mind boggling card trick
| 15rust
| amu14 |
from itertools import count, islice, chain
import time
def mian_chowla():
mc = [1]
yield mc[-1]
psums = set([2])
newsums = set([])
for trial in count(2):
for n in chain(mc, [trial]):
sum = n + trial
if sum in psums:
newsums.clear()
break
newsums.add(sum)
else:
psums |= newsums
newsums.clear()
mc.append(trial)
yield trial
def pretty(p, t, s, f):
print(p, t, .join(str(n) for n in (islice(mian_chowla(), s, f))))
if __name__ == '__main__':
st = time.time()
ts =
pretty(, ts, 0, 30)
pretty(, ts, 90, 100)
print(, (time.time()-st) * 1000, ) | 571Mian-Chowla sequence
| 3python
| nrkiz |
package main
import (
"fmt"
"math"
"sort"
)
type Patient struct {
id int
lastName string
} | 578Merge and aggregate datasets
| 0go
| wcyeg |
null | 560Multiplication tables
| 16scala
| d7ong |
from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u
macros = Macros()
@macros.expr
def expand(tree, **kw):
addition = 10
return q[lambda x: x * ast[tree] + u[addition]] | 572Metaprogramming
| 3python
| thpfw |
int main()
{
int *ints = malloc(SIZEOF_MEMB*NMEMB);
ints = realloc(ints, sizeof(int)*(NMEMB+1));
int *int2 = calloc(NMEMB, SIZEOF_MEMB);
free(ints); free(int2);
return 0;
} | 579Memory allocation
| 5c
| lx1cy |
import Data.List
import Data.Maybe
import System.IO (readFile)
import Text.Read (readMaybe)
import Control.Applicative ((<|>))
newtype DB = DB { entries :: [Patient] }
deriving Show
instance Semigroup DB where
DB a <> DB b = normalize $ a <> b
instance Monoid DB where
mempty = DB []
normalize :: [Patient] -> DB
normalize = DB
. map mconcat
. groupBy (\x y -> pid x == pid y)
. sortOn pid
data Patient = Patient { pid :: String
, name :: Maybe String
, visits :: [String]
, scores :: [Float] }
deriving Show
instance Semigroup Patient where
Patient p1 n1 v1 s1 <> Patient p2 n2 v2 s2 =
Patient (fromJust $ Just p1 <|> Just p2)
(n1 <|> n2)
(v1 <|> v2)
(s1 <|> s2)
instance Monoid Patient where
mempty = Patient mempty mempty mempty mempty
readDB :: String -> DB
readDB = normalize
. mapMaybe readPatient
. readCSV
readPatient r = do
i <- lookup "PATIENT_ID" r
let n = lookup "LASTNAME" r
let d = lookup "VISIT_DATE" r >>= readDate
let s = lookup "SCORE" r >>= readMaybe
return $ Patient i n (maybeToList d) (maybeToList s)
where
readDate [] = Nothing
readDate d = Just d
readCSV :: String -> [(String, String)]
readCSV txt = zip header <$> body
where
header:body = splitBy ',' <$> lines txt
splitBy ch = unfoldr go
where
go [] = Nothing
go s = Just $ drop 1 <$> span (/= ch) s | 578Merge and aggregate datasets
| 8haskell
| 6ph3k |
def mod(m, n)
result = m % n
if result < 0 then
result = result + n
end
return result
end
def getA004290(n)
if n == 1 then
return 1
end
arr = Array.new(n) { Array.new(n, 0) }
arr[0][0] = 1
arr[0][1] = 1
m = 0
while true
m = m + 1
if arr[m - 1][mod(-10 ** m, n)] == 1 then
break
end
arr[m][0] = 1
for k in 1 .. n - 1
arr[m][k] = [arr[m - 1][k], arr[m - 1][mod(k - 10 ** m, n)]].max
end
end
r = 10 ** m
k = mod(-r, n)
(m - 1).downto(1) { |j|
if arr[j - 1][k] == 0 then
r = r + 10 ** j
k = mod(k - 10 ** j, n)
end
}
if k == 1 then
r = r + 1
end
return r
end
testCases = Array(1 .. 10)
testCases.concat(Array(95 .. 105))
testCases.concat([297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878])
for n in testCases
result = getA004290(n)
print % [n, result, n, result / n]
end | 567Minimum positive multiple in base 10 using only 0 and 1
| 14ruby
| d7ens |
a = 2988348162058574136915891421498819466320163312926952423791023078876139
b = 2351399303373464486466122544523690094744975233415544072992656881240319
m = 10**40
puts a.pow(b, m) | 566Modular exponentiation
| 14ruby
| kzvhg |
use num::bigint::BigInt;
use num::bigint::ToBigInt; | 566Modular exponentiation
| 15rust
| b3ukx |
use Time::HiRes qw(sleep gettimeofday);
local $| = 1;
my $beats_per_minute = shift || 72;
my $beats_per_bar = shift || 4;
my $i = 0;
my $duration = 60 / $beats_per_minute;
my $base_time = gettimeofday() + $duration;
for (my $next_time = $base_time ; ; $next_time += $duration) {
if ($i++ % $beats_per_bar == 0) {
print "\nTICK";
}
else {
print " tick";
}
sleep($next_time - gettimeofday());
} | 573Metronome
| 2perl
| xlvw8 |
require 'set'
n, ts, mc, sums = 100, [], [1], Set.new
sums << 2
st = Time.now
for i in (1 .. (n-1))
for j in mc[i-1]+1 .. Float::INFINITY
mc[i] = j
for k in (0 .. i)
if (sums.include?(sum = mc[k]+j))
ts.clear
break
end
ts << sum
end
if (ts.length > 0)
sums = sums | ts
break
end
end
end
et = (Time.now - st) * 1000
s =
puts
puts
puts | 571Mian-Chowla sequence
| 14ruby
| fjpdr |
'%C%' <- function(n, k) choose(n, k)
5 %C% 2 | 572Metaprogramming
| 13r
| igjo5 |
use strict 'vars';
use warnings;
use PDL;
use PDL::Image2D;
my $image = rpic 'plasma.png';
my $smoothed = med2d $image, ones(3,3), {Boundary => Truncate};
wpic $smoothed, 'plasma_median.png'; | 575Median filter
| 2perl
| 4oo5d |
import scala.collection.mutable.ListBuffer
object MinimumNumberOnlyZeroAndOne {
def main(args: Array[String]): Unit = {
for (n <- getTestCases) {
val result = getA004290(n)
println(s"A004290($n) = $result = $n * ${result / n}")
}
}
def getTestCases: List[Int] = {
val testCases = ListBuffer.empty[Int]
for (i <- 1 to 10) {
testCases += i
}
for (i <- 95 to 105) {
testCases += i
}
for (i <- Array(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) {
testCases += i
}
testCases.toList
}
def getA004290(n: Int): BigInt = {
if (n == 1) {
return 1
}
val L = Array.ofDim[Int](n, n)
for (i <- 2 until n) {
L(0)(i) = 0
}
L(0)(0) = 1
L(0)(1) = 1
var m = 0
val ten = BigInt(10)
val nBi = BigInt(n)
var loop = true
while (loop) {
m = m + 1
if (L(m - 1)(mod(-ten.pow(m), nBi).intValue()) == 1) {
loop = false
} else {
L(m)(0) = 1
for (k <- 1 until n) {
L(m)(k) = math.max(L(m - 1)(k), L(m - 1)(mod(BigInt(k) - ten.pow(m), nBi).toInt))
}
}
}
var r = ten.pow(m)
var k = mod(-r, nBi)
for (j <- m - 1 to 1 by -1) {
if (L(j - 1)(k.toInt) == 0) {
r = r + ten.pow(j)
k = mod(k - ten.pow(j), nBi)
}
}
if (k == 1) {
r = r + 1
}
r
}
def mod(m: BigInt, n: BigInt): BigInt = {
var result = m % n
if (result < 0) {
result = result + n
}
result
}
} | 567Minimum positive multiple in base 10 using only 0 and 1
| 16scala
| 3bszy |
import scala.math.BigInt
val a = BigInt(
"2988348162058574136915891421498819466320163312926952423791023078876139")
val b = BigInt(
"2351399303373464486466122544523690094744975233415544072992656881240319")
println(a.modPow(b, BigInt(10).pow(40))) | 566Modular exponentiation
| 16scala
| amg1n |
import time
import threading
sem = threading.Semaphore(4)
workers = []
running = 1
def worker():
me = threading.currentThread()
while 1:
sem.acquire()
try:
if not running:
break
print '%s acquired semaphore'% me.getName()
time.sleep(2.0)
finally:
sem.release()
time.sleep(0.01)
for i in range(10):
t = threading.Thread(name=str(i), target=worker)
workers.append(t)
t.start()
try:
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
running = 0
for t in workers:
t.join() | 570Metered concurrency
| 3python
| fj1de |
MAX=1000
m[1]=1
for n in `seq 2 $MAX`
do
m[n]=1
for k in `seq 2 $n`
do
m[n]=$((m[n]-m[n/k]))
done
done
echo 'The first 99 Mertens numbers are:'
echo -n ' '
for n in `seq 1 99`
do
printf '%2d ' ${m[n]}
test $((n%10)) -eq 9 && echo
done
zero=0
cross=0
for n in `seq 1 $MAX`
do
if [ ${m[n]} -eq 0 ]
then
((zero++))
test ${m[n-1]} -ne 0 && ((cross++))
fi
done
echo "M(N) is zero $zero times."
echo "M(N) crosses zero $cross times." | 580Mertens function
| 4bash
| fj5d8 |
use Bit::Vector::Minimal qw();
my $vec = Bit::Vector::Minimal->new(size => 24);
my %rs232 = reverse (
1 => 'PG Protective ground',
2 => 'TD Transmitted data',
3 => 'RD Received data',
4 => 'RTS Request to send',
5 => 'CTS Clear to send',
6 => 'DSR Data set ready',
7 => 'SG Signal ground',
8 => 'CD Carrier detect',
9 => '+ voltage (testing)',
10 => '- voltage (testing)',
12 => 'SCD Secondary CD',
13 => 'SCS Secondary CTS',
14 => 'STD Secondary TD',
15 => 'TC Transmit clock',
16 => 'SRD Secondary RD',
17 => 'RC Receiver clock',
19 => 'SRS Secondary RTS',
20 => 'DTR Data terminal ready',
21 => 'SQD Signal quality detector',
22 => 'RI Ring indicator',
23 => 'DRS Data rate select',
24 => 'XTC External clock',
);
$vec->set($rs232{'RD Received data'}, 1);
$vec->get($rs232{'TC Transmit clock'}); | 577Memory layout of a data structure
| 2perl
| 0u2s4 |
import Image, ImageFilter
im = Image.open('image.ppm')
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm') | 575Median filter
| 3python
| gii4h |
char * mid3(int n)
{
static char buf[32];
int l;
sprintf(buf, , n > 0 ? n : -n);
l = strlen(buf);
if (l < 3 || !(l & 1)) return 0;
l = l / 2 - 1;
buf[l + 3] = 0;
return buf + l;
}
int main(void)
{
int x[] = {123, 12345, 1234567, 987654321, 10001, -10001,
-123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0,
1234567890};
int i;
char *m;
for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) {
if (!(m = mid3(x[i])))
m = ;
printf(, x[i], m);
}
return 0;
} | 581Middle three digits
| 5c
| 6pr32 |
public func mianChowla(n: Int) -> [Int] {
var mc = Array(repeating: 0, count: n)
var ls = [2: true]
var sum = 0
mc[0] = 1
for i in 1..<n {
var lsx = [Int]()
jLoop: for j in (mc[i-1]+1)... {
mc[i] = j
for k in 0...i {
sum = mc[k] + j
if ls[sum]?? false {
lsx = []
continue jLoop
}
lsx.append(sum)
}
for n in lsx {
ls[n] = true
}
break
}
}
return mc
}
let seq = mianChowla(n: 100)
print("First 30 terms in sequence are: \(Array(seq.prefix(30)))")
print("Terms 91 to 100 are: \(Array(seq[90..<100]))") | 571Mian-Chowla sequence
| 17swift
| d7bnh |
from ctypes import Structure, c_int
rs232_9pin = .split()
rs232_25pin = (
).split()
class RS232_9pin(Structure):
_fields_ = [(__, c_int, 1) for __ in rs232_9pin]
class RS232_25pin(Structure):
_fields_ = [(__, c_int, 1) for __ in rs232_25pin] | 577Memory layout of a data structure
| 3python
| 85v0o |
use warnings;
use strict;
{ package Local::Field;
use constant {
REAL => 0,
SHOW => 1,
COUNT => 2,
};
sub new {
my ($class, $width, $height, $percent) = @_;
my $field;
for my $x (1 .. $width) {
for my $y (1 .. $height) {
$field->[$x - 1][$y - 1][REAL] = ' ';
$field->[$x - 1][$y - 1][SHOW] = '.';
}
}
for (1 .. $percent / 100 * $width * $height) {
my ($x, $y) = map int rand $_, $width, $height;
redo if 'm' eq $field->[$x][$y][REAL];
$field->[$x][$y][REAL] = 'm';
for my $i ($x - 1 .. $x + 1) {
for my $j ($y - 1 .. $y + 1) {
$field->[$i][$j][COUNT]++
if $i >= 0 and $j >= 0
and $i <= $
}
}
}
bless $field, $class;
}
sub show {
my ($self) = @_;
print "\n ";
printf '%2d ', $_ + 1 for 0 .. $
print "\n";
for my $row (0 .. $
printf '%2d ', 1 + $row;
for my $column (0 .. $
print $self->[$column][$row][SHOW], ' ';
}
print "\n";
}
}
sub mark {
my ($self, $x, $y) = @_;
$_-- for $x, $y;
if ('.' eq $self->[$x][$y][SHOW]) {
$self->[$x][$y][SHOW] = '?';
} elsif ('?' eq $self->[$x][$y][SHOW]) {
$self->[$x][$y][SHOW] = '.';
}
}
sub end {
my $self = shift;
for my $y (0 .. $
for my $x (0 .. $
$self->[$x][$y][SHOW] = '!' if '.' eq $self->[$x][$y][SHOW]
and 'm' eq $self->[$x][$y][REAL];
$self->[$x][$y][SHOW] = 'x' if '?' eq $self->[$x][$y][SHOW]
and 'm' ne $self->[$x][$y][REAL];
}
}
$self->show;
exit;
}
sub _declassify {
my ($self, $x, $y) = @_;
return if '.' ne $self->[$x][$y][SHOW];
if (' ' eq $self->[$x][$y][REAL] and '.' eq $self->[$x][$y][SHOW]) {
$self->[$x][$y][SHOW] = $self->[$x][$y][COUNT] || ' ';
}
return if ' ' ne $self->[$x][$y][SHOW];
for my $i ($x - 1 .. $x + 1) {
next if $i < 0 or $i > $
for my $j ($y - 1 .. $y + 1) {
next if $j < 0 or $j > $
no warnings 'recursion';
$self->_declassify($i, $j);
}
}
}
sub clear {
my ($self, $x, $y) = @_;
$_-- for $x, $y;
return unless '.' eq $self->[$x][$y][SHOW];
print "You lost.\n" and $self->end if 'm' eq $self->[$x][$y][REAL];
$self->_declassify($x, $y);
}
sub remain {
my $self = shift;
my $unclear = 0;
for my $column (@$self) {
for my $cell (@$column) {
$unclear++ if '.' eq $cell->[SHOW];
}
}
return $unclear;
}
}
sub help {
print << '__HELP__';
Commands:
h ... help
q ... quit
m X Y ... mark/unmark X Y
c X Y ... clear X Y
__HELP__
}
my ($width, $height, $percent) = @ARGV;
$width ||= 6;
$height ||= 4;
$percent ||= 15;
my $field = 'Local::Field'->new($width, $height, $percent);
my $help = 1;
while (1) {
$field->show;
help() if $help;
$help = 0;
my $remain = $field->remain;
last if 0 == $remain;
print "Cells remaining: $remain.\n";
my $command = <STDIN>;
exit if $command =~ /^q/i;
if ($command =~ /^m.*?([0-9]+).*?([0-9]+)/i) {
$field->mark($1, $2);
} elsif ($command =~ /^c.*?([0-9]+).*?([0-9]+)/i) {
$field->clear($1, $2);
} elsif ($command =~ /^h/i) {
$help = 1;
} else {
print "Huh?\n";
}
}
print "You won!\n"; | 568Minesweeper game
| 2perl
| 9eomn |
import BigInt
func modPow<T: BinaryInteger>(n: T, e: T, m: T) -> T {
guard e!= 0 else {
return 1
}
var res = T(1)
var base = n% m
var exp = e
while true {
if exp & 1 == 1 {
res *= base
res%= m
}
if exp == 1 {
return res
}
exp /= 2
base *= base
base%= m
}
}
let a = BigInt("2988348162058574136915891421498819466320163312926952423791023078876139")
let b = BigInt("2351399303373464486466122544523690094744975233415544072992656881240319")
print(modPow(n: a, e: b, m: BigInt(10).power(40))) | 566Modular exponentiation
| 17swift
| ht2j0 |
require 'thread'
class Semaphore
def initialize(size = 1)
@queue = SizedQueue.new(size)
size.times { acquire }
end
def acquire
tap { @queue.push(nil) }
end
def release
tap { @queue.pop }
end
def count
@queue.length
end
def synchronize
release
yield
ensure
acquire
end
end
def foo(id, sem)
sem.synchronize do
puts
sleep(2)
end
end
threads = []
n = 5
s = Semaphore.new(3)
n.times do |i|
threads << Thread.new { foo i, s }
end
threads.each(&:join) | 570Metered concurrency
| 14ruby
| zketw |
null | 570Metered concurrency
| 15rust
| 3bwz8 |
class IDVictim
attr_accessor :name, :birthday, :gender, :hometown
def self.new_element(element)
attr_accessor element
end
end | 572Metaprogramming
| 14ruby
| 3baz7 |
int* mertens_numbers(int max) {
int* m = malloc((max + 1) * sizeof(int));
if (m == NULL)
return m;
m[1] = 1;
for (int n = 2; n <= max; ++n) {
m[n] = 1;
for (int k = 2; k <= n; ++k)
m[n] -= m[n/k];
}
return m;
}
int main() {
const int max = 1000;
int* mertens = mertens_numbers(max);
if (mertens == NULL) {
fprintf(stderr, );
return 1;
}
printf();
const int count = 200;
for (int i = 0, column = 0; i < count; ++i) {
if (column > 0)
printf();
if (i == 0)
printf();
else
printf(, mertens[i]);
++column;
if (column == 20) {
printf();
column = 0;
}
}
int zero = 0, cross = 0, previous = 0;
for (int i = 1; i <= max; ++i) {
int m = mertens[i];
if (m == 0) {
++zero;
if (previous != 0)
++cross;
}
previous = m;
}
free(mertens);
printf(, zero, max);
printf(, cross, max);
return 0;
} | 580Mertens function
| 5c
| zkgtx |
class Pixmap
def median_filter(radius=3)
radius += 1 if radius.even?
filtered = self.class.new(@width, @height)
pb = ProgressBar.new(@height) if $DEBUG
@height.times do |y|
@width.times do |x|
window = []
(x - radius).upto(x + radius).each do |win_x|
(y - radius).upto(y + radius).each do |win_y|
win_x = 0 if win_x < 0
win_y = 0 if win_y < 0
win_x = @width-1 if win_x >= @width
win_y = @height-1 if win_y >= @height
window << self[win_x, win_y]
end
end
filtered[x, y] = window.sort[window.length / 2]
end
pb.update(y) if $DEBUG
end
pb.close if $DEBUG
filtered
end
end
class RGBColour
def luminosity
Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue)
end
def to_grayscale
l = luminosity
self.class.new(l, l, l)
end
def <=>(other)
self.luminosity <=> other.luminosity
end
end
class ProgressBar
def initialize(max)
$stdout.sync = true
@progress_max = max
@progress_pos = 0
@progress_view = 68
$stdout.print
end
def update(n)
new_pos = n * @progress_view/@progress_max
if new_pos > @progress_pos
@progress_pos = new_pos
$stdout.print '='
end
end
def close
$stdout.puts '=]'
end
end
bitmap = Pixmap.open('file')
filtered = bitmap.median_filter | 575Median filter
| 14ruby
| 7ddri |
import time
def main(bpm = 72, bpb = 4):
sleep = 60.0 / bpm
counter = 0
while True:
counter += 1
if counter% bpb:
print 'tick'
else:
print 'TICK'
time.sleep(sleep)
main() | 573Metronome
| 3python
| q2uxi |
class CountingSemaphore(var maxCount: Int) {
private var lockCount = 0
def acquire(): Unit = {
while ( {
lockCount >= maxCount
}) wait()
lockCount += 1
}
def release(): Unit = {
if (lockCount > 0) {
lockCount -= 1
notifyAll()
}
}
def getCount: Int = lockCount
}
object Worker {
def main(args: Array[String]): Unit = {
val (lock, crew) = (new CountingSemaphore(3), new Array[Worker](5))
for { i <- 0 until 5} {
crew(i) = new Worker(lock, i)
crew(i).start()
}
}
} | 570Metered concurrency
| 16scala
| masyc |
null | 572Metaprogramming
| 15rust
| 6pe3l |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.