code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import java.util.HashMap;
import java.util.Map;
public class MutualRecursion {
public static void main(final String args[]) {
int max = 20;
System.out.printf("First%d values of the Female sequence: %n", max);
for (int i = 0; i < max; i++) {
System.out.printf(" f(%d) =%d%n", i, f(i));
}
System.out.printf("First%d values of the Male sequence: %n", max);
for (int i = 0; i < 20; i++) {
System.out.printf(" m(%d) =%d%n", i, m(i));
}
}
private static Map<Integer,Integer> F_MAP = new HashMap<>();
private static int f(final int n) {
if ( F_MAP.containsKey(n) ) {
return F_MAP.get(n);
}
int fn = n == 0 ? 1 : n - m(f(n - 1));
F_MAP.put(n, fn);
return fn;
}
private static Map<Integer,Integer> M_MAP = new HashMap<>();
private static int m(final int n) {
if ( M_MAP.containsKey(n) ) {
return M_MAP.get(n);
}
int mn = n == 0 ? 0 : n - f(m(n - 1));
M_MAP.put(n, mn);
return mn;
}
} | 542Mutual recursion
| 9java
| n74ih |
use strict;
use feature 'say';
use Data::Monad::List;
my @cartesian = [(
list_flat_map_multi { scalar_list(join '', @_) }
scalar_list(0..1),
scalar_list(0..1),
scalar_list(0..1)
)->scalars];
say join "\n", @{shift @cartesian};
say '';
my @triples = [(
list_flat_map_multi { scalar_list(
{ $_[0] < $_[1] && $_[0]**2+$_[1]**2 == $_[2]**2 ? join(',',@_) : () }
) }
scalar_list(1..10),
scalar_list(1..10),
scalar_list(1..10)
)->scalars];
for (@{shift @triples}) {
say keys %$_ if keys %$_;
} | 553Monads/List monad
| 2perl
| lq4c5 |
use strict;
use warnings;
use Statistics::Regression;
my @y = (52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46);
my @x = ( 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83);
my @model = ('const', 'X', 'X**2');
my $reg = Statistics::Regression->new( '', [@model] );
$reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1;
my @coeff = $reg->theta();
printf "%-6s%8.3f\n", $model[$_], $coeff[$_] for 0..@model-1; | 548Multiple regression
| 2perl
| 61436 |
import Control.Monad
import Data.List
queens :: Int -> [[Int]]
queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where
oneMoreQueen (y,d) _ = [(x:y, delete x d) | x <- d, safe x] where
safe x = and [x /= c + n && x /= c - n | (n,c) <- zip [1..] y]
printSolution y = do
let n = length y
mapM_ (\x -> putStrLn [if z == x then 'Q' else '.' | z <- [1..n]]) y
putStrLn ""
main = mapM_ printSolution $ queens 6 | 543N-queens problem
| 8haskell
| yak66 |
function f(num) {
return (num === 0) ? 1 : num - m(f(num - 1));
}
function m(num) {
return (num === 0) ? 0 : num - f(m(num - 1));
}
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(
function (x, i) { return m + i; }
);
}
var a = range(0, 19); | 542Mutual recursion
| 10javascript
| 3phz0 |
package main
import (
"fmt"
"strconv"
)
type maybe struct{ value *int }
func (m maybe) bind(f func(p *int) maybe) maybe {
return f(m.value)
}
func unit(p *int) maybe {
return maybe{p}
}
func decrement(p *int) maybe {
if p == nil {
return unit(nil)
} else {
q := *p - 1
return unit(&q)
}
}
func triple(p *int) maybe {
if p == nil {
return unit(nil)
} else {
q := (*p) * 3
return unit(&q)
}
}
func main() {
i, j, k := 3, 4, 5
for _, p := range []*int{&i, &j, nil, &k} {
m1 := unit(p)
m2 := m1.bind(decrement).bind(triple)
var s1, s2 string = "none", "none"
if m1.value != nil {
s1 = strconv.Itoa(*m1.value)
}
if m2.value != nil {
s2 = strconv.Itoa(*m2.value)
}
fmt.Printf("%4s ->%s\n", s1, s2)
}
} | 555Monads/Maybe monad
| 0go
| 05isk |
null | 550Move-to-front algorithm
| 11kotlin
| k3qh3 |
class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, []);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, )
->bind($m($root, ))
->bind($m($addOne, ))
->bind($m($half, ));
print ;
print join(, $result->logs()); | 554Monads/Writer monad
| 12php
| n7zig |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar()
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return cls(value)
def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return MList(chain.from_iterable(map(func, self)))
def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
return self.bind(func)
if __name__ == :
print(
MList([1, 99, 4])
.bind(lambda val: MList([val + 1]))
.bind(lambda val: MList([f]))
)
print(
MList([1, 99, 4])
>> (lambda val: MList([val + 1]))
>> (lambda val: MList([f]))
)
print(
MList(range(1, 6)).bind(
lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
)
)
print(
MList(range(1, 26)).bind(
lambda x: MList(range(x + 1, 26)).bind(
lambda y: MList(range(y + 1, 26)).bind(
lambda z: MList([(x, y, z)])
if x * x + y * y == z * z
else MList([])
)
)
)
) | 553Monads/List monad
| 3python
| 2sglz |
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1))
print $ Nothing >>= (return . (*2)) >>= (return . (+1)) | 555Monads/Maybe monad
| 8haskell
| cxv94 |
null | 550Move-to-front algorithm
| 1lua
| b6ska |
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int main(void) {
printf(, mul_inv(42, 2017));
return 0;
} | 556Modular inverse
| 5c
| gn745 |
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar()
class Writer(Generic[T]):
def __init__(self, value: Union[T, Writer[T]], *msgs: str):
if isinstance(value, Writer):
self.value: T = value.value
self.msgs: List[str] = value.msgs + list(msgs)
else:
self.value = value
self.msgs = list(f for msg in msgs)
def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
writer = func(self.value)
return Writer(writer, *self.msgs)
def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
return self.bind(func)
def __str__(self):
return f
def __repr__(self):
return f{', '.join(reversed(self.msgs))}\
def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
@functools.wraps(func)
def wrapped(value):
return Writer(func(value), msg)
return wrapped
if __name__ == :
square_root = lift(math.sqrt, )
add_one = lift(lambda x: x + 1, )
half = lift(lambda x: x / 2, )
print(Writer(5, ) >> square_root >> add_one >> half) | 554Monads/Writer monad
| 3python
| rdkgq |
import numpy as np
height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63,
1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83]
weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93,
61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46]
X = np.mat(height**np.arange(3)[:, None])
y = np.mat(weight)
print(y * X.T * (X*X.T).I) | 548Multiple regression
| 3python
| yag6q |
use 5.10.0;
my %irregulars = ( 1 => 'st',
2 => 'nd',
3 => 'rd',
11 => 'th',
12 => 'th',
13 => 'th');
sub nth
{
my $n = shift;
$n .
($irregulars{$n % 100} // $irregulars{$n % 10} // 'th');
}
sub range { join ' ', map { nth($_) } @{$_[0]} }
print range($_), "\n" for ([0..25], [250..265], [1000..1025]); | 540N'th
| 2perl
| wlce6 |
(function () {
'use strict'; | 555Monads/Maybe monad
| 10javascript
| 9w2ml |
class Array
def bind(f)
flat_map(&f)
end
def self.unit(*args)
args
end
def self.lift(f)
-> e { self.unit(f[e]) }
end
end
inc = -> n { n + 1 }
str = -> n { n.to_s }
listy_inc = Array.lift(inc)
listy_str = Array.lift(str)
Array.unit(3,4,5).bind(listy_inc).bind(listy_str)
doub = -> n { 2*n }
listy_doub = Array.lift(doub)
[3,4,5].bind(listy_inc).bind(listy_doub)
comp = -> f, g {-> x {f[g[x]]}}
[3,4,5].bind(comp[listy_doub, listy_inc])
class Array
def bind_comp(f, g)
bind(g).bind(f)
end
end
[3,4,5].bind_comp(listy_doub, listy_inc) | 553Monads/List monad
| 14ruby
| u87vz |
object MultiDimensionalArray extends App { | 547Multi-dimensional array
| 16scala
| qv3xw |
x <- c(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83)
y <- c(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46)
lm( y ~ x + I(x^2)) | 548Multiple regression
| 13r
| tkvfz |
package main
import "fmt"
func multiFactorial(n, k int) int {
r := 1
for ; n > 1; n -= k {
r *= n
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Print("degree ", k, ":")
for n := 1; n <= 10; n++ {
fmt.Print(" ", multiFactorial(n, k))
}
fmt.Println()
}
} | 552Multifactorial
| 0go
| lqgcw |
null | 555Monads/Maybe monad
| 11kotlin
| irfo4 |
double pi(double tolerance)
{
double x, y, val, error;
unsigned long sampled = 0, hit = 0, i;
do {
for (i = 1000000; i; i--, sampled++) {
x = rand() / (RAND_MAX + 1.0);
y = rand() / (RAND_MAX + 1.0);
if (x * x + y * y < 1) hit ++;
}
val = (double) hit / sampled;
error = sqrt(val * (1 - val) / sampled) * 4;
val *= 4;
fprintf(stderr, ,
val, error, sampled/1000000);
} while (!hit || error > tolerance);
return val;
}
int main()
{
printf(, pi(3e-4));
return 0;
} | 557Monte Carlo methods
| 5c
| 2svlo |
mulfac :: (Num a, Enum a) => a -> [a]
mulfac k = 1: s
where
s = [1 .. k] <> zipWith (*) s [k + 1 ..]
mulfac1 :: (Num a, Enum a) => a -> a -> a
mulfac1 k n = product [n, n - k .. 1]
main :: IO ()
main =
mapM_
(print . take 10 . tail . mulfac)
[1 .. 5] | 552Multifactorial
| 8haskell
| 1msps |
function nth($num) {
$os = ;
if ($num % 100 <= 10 or $num % 100 > 20) {
switch ($num % 10) {
case 1:
$os = ;
break;
case 2:
$os = ;
break;
case 3:
$os = ;
break;
}
}
return $num . $os;
}
foreach ([[0,25], [250,265], [1000,1025]] as $i) {
while ($i[0] <= $i[1]) {
echo nth($i[0]) . ;
$i[0]++;
}
echo ;
} | 540N'th
| 12php
| lqxcj |
null | 542Mutual recursion
| 11kotlin
| sulq7 |
null | 555Monads/Maybe monad
| 1lua
| n7ti8 |
alpha2morse() {
local -A alpha_assoc=( [A]='.-' [B]='-...' [C]='-.-.' [D]='-..' [E]='.' \
[F]='..-.' [G]='--.' [H]='....' [I]='..' [J]='.---' \
[K]='-.-' [L]='.-..' [M]='--' [N]='-.' [O]='---' \
[P]='.--.' [Q]='--.-' [R]='.-.' [S]='...' [T]='-' \
[U]='..-' [V]='...-' [W]='.--' [X]='-..-' [Y]='-.--' [Z]='--..' \
[0]='-----' [1]='.----' [2]='..---' [3]='...--' [4]='....-' \
[5]='.....' [6]='-....' [7]='--...' [8]='----..' [9]='----.' )
if [[ "${
echo -ne "Usage: ${FUNCNAME[0]} arguments...\n \
${FUNCNAME[0]} is an IMC transmitter. \n \
It'll transmit your messages to International Morse Code.\n" >&2
return 1
fi
while [[ -n "${1}" ]]; do
for (( i = 0; i < ${
local letter="${1:${i}:1}"
for (( y = 0; y < ${
case "${alpha_assoc[${letter^^}]:${y}:1}" in
".") echo -n "dot "; play -q -n -c2 synth .1 2> /dev/null || sleep .1 ;;
"-") echo -n "dash "; play -q -n -c2 synth .3 2> /dev/null || sleep .3 ;;
esac
sleep .1
done
echo
sleep .3
done
echo
sleep .7
shift
done
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
alpha2morse "${@}"
fi | 558Morse code
| 4bash
| ogo8a |
(ns test-p.core
(:require [clojure.math.numeric-tower :as math]))
(defn extended-gcd
"The extended Euclidean algorithm--using Clojure code from RosettaCode for Extended Eucliean
(see http://en.wikipedia.orwiki/Extended_Euclidean_algorithm)
Returns a list containing the GCD and the Bzout coefficients
corresponding to the inputs with the result: gcd followed by bezout coefficients "
[a b]
(cond (zero? a) [(math/abs b) 0 1]
(zero? b) [(math/abs a) 1 0]
:else (loop [s 0
s0 1
t 1
t0 0
r (math/abs b)
r0 (math/abs a)]
(if (zero? r)
[r0 s0 t0]
(let [q (quot r0 r)]
(recur (- s0 (* q s)) s
(- t0 (* q t)) t
(- r0 (* q r)) r))))))
(defn mul_inv
" Get inverse using extended gcd. Extended GCD returns
gcd followed by bezout coefficients. We want the 1st coefficients
(i.e. second of extend-gcd result). We compute mod base so result
is between 0..(base-1) "
[a b]
(let [b (if (neg? b) (- b) b)
a (if (neg? a) (- b (mod (- a) b)) a)
egcd (extended-gcd a b)]
(if (= (first egcd) 1)
(mod (second egcd) b)
(str "No inverse since gcd is: " (first egcd)))))
(println (mul_inv 42 2017))
(println (mul_inv 40 1))
(println (mul_inv 52 -217))
(println (mul_inv -486 217))
(println (mul_inv 40 2018)) | 556Modular inverse
| 6clojure
| k3phs |
require 'matrix'
def regression_coefficients y, x
y = Matrix.column_vector y.map { |i| i.to_f }
x = Matrix.columns x.map { |xi| xi.map { |i| i.to_f }}
(x.t * x).inverse * x.t * y
end | 548Multiple regression
| 14ruby
| 9w7mz |
public class NQueens {
private static int[] b = new int[8];
private static int s = 0;
static boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x ||
t == x - i ||
t == x + i) {
return true;
}
}
return false;
}
public static void putboard() {
System.out.println("\n\nSolution " + (++s));
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
System.out.print((b[y] == x) ? "|Q" : "|_");
}
System.out.println("|");
}
}
public static void main(String[] args) {
int y = 0;
b[0] = -1;
while (y >= 0) {
do {
b[y]++;
} while ((b[y] < 8) && unsafe(y));
if (b[y] < 8) {
if (y < 7) {
b[++y] = -1;
} else {
putboard();
}
} else {
y--;
}
}
}
} | 543N-queens problem
| 9java
| dj4n9 |
use strict;
use warnings;
use Data::Monad::Maybe;
sub safeReciprocal { ( $_[0] == 0 ) ? nothing : just( 1 / $_[0] ) }
sub safeRoot { ( $_[0] < 0 ) ? nothing : just( sqrt( $_[0] ) ) }
sub safeLog { ( $_[0] <= 0 ) ? nothing : just( log ( $_[0] ) ) }
print join(' ', map {
my $safeLogRootReciprocal = just($_)->flat_map( \&safeReciprocal )
->flat_map( \&safeRoot )
->flat_map( \&safeLog );
$safeLogRootReciprocal->is_nothing ? "NaN" : $safeLogRootReciprocal->value;
} (-2, -1, -0.5, 0, exp (-1), 1, 2, exp(1), 3, 4, 5) ), "\n"; | 555Monads/Maybe monad
| 2perl
| rdhgd |
use strict;
use warnings;
sub encode {
my ($str) = @_;
my $table = join '', 'a' .. 'z';
map {
$table =~ s/(.*?)$_/$_$1/ or die;
length($1);
} split //, $str;
}
sub decode {
my $table = join '', 'a' .. 'z';
join "", map {
$table =~ s/(.{$_})(.)/$2$1/ or die;
$2;
} @_;
}
for my $test ( qw(broood bananaaa hiphophiphop) ) {
my @encoded = encode($test);
print "$test: @encoded\n";
my $decoded = decode(@encoded);
print "in" x ( $decoded ne $test );
print "correctly decoded to $decoded\n";
} | 550Move-to-front algorithm
| 2perl
| 3pvzs |
use SDL;
use SDL::Events;
use SDLx::App;
my $app = SDLx::App->new;
$app->add_event_handler( sub {
my $event = shift;
if( $event->type == SDL_MOUSEMOTION ) {
printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y );
$app->stop
}
} );
$app->run; | 551Mouse position
| 2perl
| sufq3 |
function queenPuzzle(rows, columns) {
if (rows <= 0) {
return [[]];
} else {
return addQueen(rows - 1, columns);
}
}
function addQueen(newRow, columns, prevSolution) {
var newSolutions = [];
var prev = queenPuzzle(newRow, columns);
for (var i = 0; i < prev.length; i++) {
var solution = prev[i];
for (var newColumn = 0; newColumn < columns; newColumn++) {
if (!hasConflict(newRow, newColumn, solution))
newSolutions.push(solution.concat([newColumn]))
}
}
return newSolutions;
}
function hasConflict(newRow, newColumn, solution) {
for (var i = 0; i < newRow; i++) {
if (solution[i] == newColumn ||
solution[i] + i == newColumn + newRow ||
solution[i] - i == newColumn - newRow) {
return true;
}
}
return false;
}
console.log(queenPuzzle(8,8)); | 543N-queens problem
| 10javascript
| 61h38 |
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar()
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if isinstance(value, Maybe):
self.value: Optional[T] = value.value
else:
self.value = value
def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]):
return self.bind(func)
def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]:
return func(self.value)
def __str__(self):
return f
def plus_one(value: Optional[int]) -> Maybe[int]:
if value is not None:
return Maybe[int](value + 1)
return Maybe[int](None)
def currency(value: Optional[int]) -> Maybe[str]:
if value is not None:
return Maybe[str](f)
return Maybe[str](None)
if __name__ == :
test_cases = [1, 99, None, 4]
for case in test_cases:
m_int = Maybe[int](case)
result = m_int >> plus_one >> currency
print(f) | 555Monads/Maybe monad
| 3python
| 7fkrm |
(defn calc-pi [iterations]
(loop [x (rand) y (rand) in 0 total 1]
(if (< total iterations)
(recur (rand) (rand) (if (<= (+ (* x x) (* y y)) 1) (inc in) in) (inc total))
(double (* (/ in total) 4)))))
(doseq [x (take 5 (iterate #(* 10 %) 10))] (println (str (format "% 8d" x) ": " (calc-pi x)))) | 557Monte Carlo methods
| 6clojure
| gnr4f |
for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i) | 541Munchausen numbers
| 3python
| 84u0o |
<?php
function symbolTable() {
$symbol = array();
for ($c = ord('a') ; $c <= ord('z') ; $c++) {
$symbol[$c - ord('a')] = chr($c);
}
return $symbol;
}
function mtfEncode($original, $symbol) {
$encoded = array();
for ($i = 0 ; $i < strlen($original) ; $i++) {
$char = $original[$i];
$position = array_search($char, $symbol);
$encoded[] = $position;
$mtf = $symbol[$position];
unset($symbol[$position]);
array_unshift($symbol, $mtf);
}
return $encoded;
}
function mtfDecode($encoded, $symbol) {
$decoded = '';
foreach ($encoded AS $position) {
$char = $symbol[$position];
$decoded .= $char;
unset($symbol[$position]);
array_unshift($symbol, $char);
}
return $decoded;
}
foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
$encoded = mtfEncode($original, symbolTable());
$decoded = mtfDecode($encoded, symbolTable());
echo
$original,
' -> [', implode(',', $encoded), ']',
' -> ', $decoded,
': ', ($original === $decoded? 'OK' : 'Error'),
PHP_EOL;
} | 550Move-to-front algorithm
| 12php
| py0ba |
char
dih[50],dah[50],medium[30],word[30],
*dd[2] = {dih,dah};
const char
*ascii = $@13311131313111113133111111113333131311333133313313313131111311311131333113313333113333313333113331113311113111113111133111333113333113131333113311331113333131313331131313313133131311133311131313131113131313111131133131311311113113133131beep0123456789use:%s [duration] dit in ms, default%d\n -n -f 440 -l%d -D%d -n -f 440 -l%d -D%d -n -D%d -n -D%d",(7-(3-1)-1)*dit);
while (NULL != fgets(sin,72,stdin))
puts(translate(sin,sout));
return 0;
} | 558Morse code
| 5c
| n7ni6 |
int main(void){
unsigned i, j, k, choice, winsbyswitch=0, door[3];
srand(time(NULL));
for(i=0; i<GAMES; i++){
door[0] = (!(rand()%2)) ? 1: 0;
if(door[0]) door[1]=door[2]=0;
else{ door[1] = (!(rand()%2)) ? 1: 0; door[2] = (!door[1]) ? 1: 0; }
choice = rand()%3;
if(((!(door[((choice+1)%3)])) && (door[((choice+2)%3)])) || (!(door[((choice+2)%3)]) && (door[((choice+1)%3)]))) winsbyswitch++;
}
printf(, GAMES, winsbyswitch, (float)winsbyswitch*100.0/(float)i);
} | 559Monty Hall problem
| 5c
| jfr70 |
public class MultiFact {
private static long multiFact(long n, int deg){
long ans = 1;
for(long i = n; i > 0; i -= deg){
ans *= i;
}
return ans;
}
public static void main(String[] args){
for(int deg = 1; deg <= 5; deg++){
System.out.print("degree " + deg + ":");
for(long n = 1; n <= 10; n++){
System.out.print(" " + multiFact(n, deg));
}
System.out.println();
}
}
} | 552Multifactorial
| 9java
| 7f1rj |
import Tkinter as tk
def showxy(event):
xm, ym = event.x, event.y
str1 = % (xm, ym)
root.title(str1)
x,y, delta = 100, 100, 10
frame.config(bg='red'
if abs(xm - x) < delta and abs(ym - y) < delta
else 'yellow')
root = tk.Tk()
frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind(, showxy)
frame.pack()
root.mainloop() | 551Mouse position
| 3python
| 05tsq |
class Maybe
def initialize(value)
@value = value
end
def map
if @value.nil?
self
else
Maybe.new(yield @value)
end
end
end
Maybe.new(3).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(nil).map { |n| 2*n }.map { |n| n+1 }
Maybe.new(3).map { |n| nil }.map { |n| n+1 }
class Maybe
class << self
alias :unit :new
end
def initialize(value)
@value = value
end
def bind
if @value.nil?
self
else
yield @value
end
end
end
Maybe.unit(3).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) }
Maybe.unit(nil).bind { |n| Maybe.unit(2*n) }.bind { |n| Maybe.unit(n+1) } | 555Monads/Maybe monad
| 14ruby
| hzpjx |
import 'dart:async';
import 'dart:html';
import 'dart:math' show Random; | 557Monte Carlo methods
| 18dart
| 61y34 |
function multifact(n, deg){
var result = n;
while (n >= deg + 1){
result *= (n - deg);
n -= deg;
}
return result;
} | 552Multifactorial
| 10javascript
| pyqb7 |
null | 543N-queens problem
| 11kotlin
| 05lsf |
fun multifactorial(n: Long, d: Int) : Long {
val r = n % d
return (1..n).filter { it % d == r } .reduce { i, p -> i * p }
}
fun main(args: Array<String>) {
val m = 5
val r = 1..10L
for (d in 1..m) {
print("%${m}s:".format( "!".repeat(d)))
r.forEach { print(" " + multifactorial(it, d)) }
println()
}
} | 552Multifactorial
| 11kotlin
| u8jvc |
Shoes.app(:title => , :width => 400, :height => 400) do
@position = para , :size => 12, :margin => 10
motion do |x, y|
@position.text =
end
end | 551Mouse position
| 14ruby
| og38v |
null | 551Mouse position
| 15rust
| ir6od |
import java.awt.MouseInfo
object MousePosition extends App {
val mouseLocation = MouseInfo.getPointerInfo.getLocation
println (mouseLocation)
} | 551Mouse position
| 16scala
| fh9d4 |
_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']
def nth(n):
return % (n, _suffix[n%10] if n% 100 <= 10 or n% 100 > 20 else 'th')
if __name__ == '__main__':
for j in range(0,1001, 250):
print(' '.join(nth(i) for i in list(range(j, j+25)))) | 540N'th
| 3python
| x2lwr |
function m(n) return n > 0 and n - f(m(n-1)) or 0 end
function f(n) return n > 0 and n - m(f(n-1)) or 1 end | 542Mutual recursion
| 1lua
| 052sd |
(import [javax.sound.sampled AudioFormat AudioSystem SourceDataLine])
(defn play [sample-rate bs]
(let [af (AudioFormat. sample-rate 8 1 true true)]
(doto (AudioSystem/getSourceDataLine af)
(.open af sample-rate)
.start
(.write bs 0 (count bs))
.drain
.close)))
(defn note [hz sample-rate ms]
(let [period (/ hz sample-rate)]
(->> (range (* sample-rate ms 1/1000))
(map #(->> (* 2 Math/PI % period)
Math/sin
(* 127 ,)
byte) ,))))
(def morse-codes
{\A ".-" \J ".---" \S "..." \1 ".----" \. ".-.-.-" \: "---..."
\B "-..." \K "-.-" \T "-" \2 "..---" \, "--..--" \
\C "-.-." \L ".-.." \U "..-" \3 "...--" \? "..--.." \= "-...-"
\D "-.." \M "--" \V "...-" \4 "....-" \' ".----." \+ ".-.-."
\E "." \N "-." \W ".--" \5 "....." \! "-.-.--" \- "-....-"
\F "..-." \O "---" \X "-..-" \6 "-...." \/ "-..-." \_ "..--.-"
\G "--." \P ".--." \Y "-.--" \7 "--..." \( "-.--." \" ".-..-."
\H "...." \Q "--.-" \Z "--.." \8 "---.." \) "-.--.-" \$ "...-..-"
\I ".." \R ".-." \0 "-----" \9 "----." \& ".-..." \@ ".--.-."
\space " "})
(def sample-rate 1024)
(let [hz 440
ms 50]
(def sounds
{\. (note hz sample-rate (* 1 ms))
\- (note hz sample-rate(* 3 ms))
:element-gap (note 0 sample-rate (* 1 ms))
:letter-gap (note 0 sample-rate (* 3 ms))
\space (note 0 sample-rate (* 1 ms))}))
(defn convert-letter [letter]
(->> (get morse-codes letter "")
(map sounds ,)
(interpose (:element-gap sounds) ,)
(apply concat ,)))
(defn morse [s]
(->> (.toUpperCase s)
(map convert-letter ,)
(interpose (:letter-gap sounds) ,)
(apply concat ,)
byte-array
(play sample-rate ,))) | 558Morse code
| 6clojure
| 3p3zr |
from __future__ import print_function
from string import ascii_lowercase
SYMBOLTABLE = list(ascii_lowercase)
def move2front_encode(strng, symboltable):
sequence, pad = [], symboltable[::]
for char in strng:
indx = pad.index(char)
sequence.append(indx)
pad = [pad.pop(indx)] + pad
return sequence
def move2front_decode(sequence, symboltable):
chars, pad = [], symboltable[::]
for indx in sequence:
char = pad[indx]
chars.append(char)
pad = [pad.pop(indx)] + pad
return ''.join(chars)
if __name__ == '__main__':
for s in ['broood', 'bananaaa', 'hiphophiphop']:
encode = move2front_encode(s, SYMBOLTABLE)
print('%14r encodes to%r'% (s, encode), end=', ')
decode = move2front_decode(encode, SYMBOLTABLE)
print('which decodes back to%r'% decode)
assert s == decode, 'Whoops!' | 550Move-to-front algorithm
| 3python
| 61u3w |
(ns monty-hall-problem
(:use [clojure.contrib.seq:only (shuffle)]))
(defn play-game [staying]
(let [doors (shuffle [:goat:goat:car])
choice (rand-int 3)
[a b] (filter #(not= choice %) (range 3))
alternative (if (=:goat (nth doors a)) b a)]
(=:car (nth doors (if staying choice alternative)))))
(defn simulate [staying times]
(let [wins (reduce (fn [counter _] (if (play-game staying) (inc counter) counter))
0
(range times))]
(str "wins " wins " times out of " times))) | 559Monty Hall problem
| 6clojure
| 1ybpy |
function multiFact (n, degree)
local fact = 1
for i = n, 2, -degree do
fact = fact * i
end
return fact
end
print("Degree\t|\tMultifactorials 1 to 10")
print(string.rep("-", 52))
for d = 1, 5 do
io.write(" " .. d, "\t| ")
for n = 1, 10 do
io.write(multiFact(n, d) .. " ")
end
print()
end | 552Multifactorial
| 1lua
| 5ohu6 |
nth <- function(n)
{
if (length(n) > 1) return(sapply(n, nth))
mod <- function(m, n) ifelse(!(m%%n), n, m%%n)
suffices <- c("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")
if (n %% 100 <= 10 || n %% 100 > 20)
suffix <- suffices[mod(n+1, 10)]
else
suffix <- 'th'
paste(n, "'", suffix, sep="")
}
range <- list(0:25, 250:275, 500:525, 750:775, 1000:1025)
sapply(range, nth) | 540N'th
| 13r
| 1mypn |
class Integer
def munchausen?
self.digits.map{|d| d**d}.sum == self
end
end
puts (1..5000).select(&:munchausen?) | 541Munchausen numbers
| 14ruby
| ir4oh |
N = 8 | 543N-queens problem
| 1lua
| 8420e |
fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000: {:?}", solutions);
} | 541Munchausen numbers
| 15rust
| n7gi4 |
object Munch {
def main(args: Array[String]): Unit = {
import scala.math.pow
(1 to 5000).foreach {
i => if (i == (i.toString.toCharArray.map(d => pow(d.asDigit,d.asDigit))).sum)
println( i + " (munchausen)")
}
}
} | 541Munchausen numbers
| 16scala
| tkjfb |
int main(void)
{
int i, j, n = 12;
for (j = 1; j <= n; j++) printf(, j, j != n ? ' ' : '\n');
for (j = 0; j <= n; j++) printf(j != n ? : );
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
printf(j < i ? : , i * j);
printf(, i);
}
return 0;
} | 560Multiplication tables
| 5c
| amb11 |
module MoveToFront
ABC = (..).to_a.freeze
def self.encode(str)
ar = ABC.dup
str.chars.each_with_object([]) do |char, memo|
memo << (i = ar.index(char))
ar = m2f(ar,i)
end
end
def self.decode(indices)
ar = ABC.dup
indices.each_with_object() do |i, str|
str << ar[i]
ar = m2f(ar,i)
end
end
private
def self.m2f(ar,i)
[ar.delete_at(i)] + ar
end
end
['broood', 'bananaaa', 'hiphophiphop'].each do |word|
p word == MoveToFront.decode(p MoveToFront.encode(p word))
end | 550Move-to-front algorithm
| 14ruby
| me4yj |
package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewInt(42)
m := big.NewInt(2017)
k := new(big.Int).ModInverse(a, m)
fmt.Println(k)
} | 556Modular inverse
| 0go
| irdog |
import Foundation
func isMnchhausen(_ n: Int) -> Bool {
let nums = String(n).map(String.init).compactMap(Int.init)
return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n
}
for i in 1...5000 where isMnchhausen(i) {
print(i)
} | 541Munchausen numbers
| 17swift
| og58k |
package main
import (
"fmt"
"math"
"math/rand"
"time"
)
func getPi(numThrows int) float64 {
inCircle := 0
for i := 0; i < numThrows; i++ { | 557Monte Carlo methods
| 0go
| qvsxz |
fn main() {
let examples = vec!["broood", "bananaaa", "hiphophiphop"];
for example in examples {
let encoded = encode(example);
let decoded = decode(&encoded);
println!(
"{} encodes to {:?} decodes to {}",
example, encoded, decoded
);
}
}
fn get_symbols() -> Vec<u8> {
(b'a'..b'z').collect()
}
fn encode(input: &str) -> Vec<usize> {
input
.as_bytes()
.iter()
.fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
let i = s.iter().position(|c| c == x).unwrap();
let c = s.remove(i);
s.insert(0, c);
o.push(i);
(o, s)
})
.0
}
fn decode(input: &[usize]) -> String {
input
.iter()
.fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
o.push(s[*x]);
let c = s.remove(*x);
s.insert(0, c);
(o, s)
})
.0
.into_iter()
.map(|c| c as char)
.collect()
} | 550Move-to-front algorithm
| 15rust
| 9wgmm |
package rosetta
import scala.annotation.tailrec
object MoveToFront {
private val R = 256
private def symbolTable = (0 until R).map(_.toChar).mkString
def encode(s: String): List[Int] = {
encode(s, symbolTable)
}
def encode(s: String, symTable: String): List[Int] = {
val table = symTable.toCharArray
@inline @tailrec def moveToFront(ch: Char, index: Int, tmpout: Char): Int = {
val tmpin = table(index)
table(index) = tmpout
if (ch != tmpin)
moveToFront(ch, index + 1, tmpin)
else {
table(0) = ch
index
}
}
@tailrec def encodeString(output: List[Int], s: List[Char]): List[Int] = s match {
case Nil => output
case x :: xs => {
encodeString(moveToFront(x, 0, table(0)) :: output, s.tail)
}
}
encodeString(Nil, s.toList).reverse
}
def decode(ints: List[Int]): String = {
decode(ints, symbolTable)
}
def decode(lst: List[Int], symTable: String): String = {
val table = symTable.toCharArray
@inline def moveToFront(c: Char, index: Int) {
for (i <- index-1 to 0 by -1)
table(i+1) = table(i)
table(0) = c
}
@tailrec def decodeList(output: List[Char], lst: List[Int]): List[Char] = lst match {
case Nil => output
case x :: xs => {
val c = table(x)
moveToFront(c, x)
decodeList(c :: output, xs)
}
}
decodeList(Nil, lst).reverse.mkString
}
def test(toEncode: String, symTable: String) {
val encoded = encode(toEncode, symTable)
println(toEncode + ": " + encoded)
val decoded = decode(encoded, symTable)
if (toEncode != decoded)
print("in")
println("correctly decoded to " + decoded)
}
}
object RosettaCodeMTF extends App {
val symTable = "abcdefghijklmnopqrstuvwxyz"
MoveToFront.test("broood", symTable)
MoveToFront.test("bananaaa", symTable)
MoveToFront.test("hiphophiphop", symTable)
} | 550Move-to-front algorithm
| 16scala
| 2sjlb |
int rand(int max) => (Math.random()*max).toInt();
class Game {
int _prize;
int _open;
int _chosen;
Game() {
_prize=rand(3);
_open=null;
_chosen=null;
}
void choose(int door) {
_chosen=door;
}
void reveal() {
if(_prize==_chosen) {
int toopen=rand(2);
if (toopen>=_prize)
toopen++;
_open=toopen;
} else {
for(int i=0;i<3;i++)
if(_prize!=i && _chosen!=i) {
_open=i;
break;
}
}
}
void change() {
for(int i=0;i<3;i++)
if(_chosen!=i && _open!=i) {
_chosen=i;
break;
}
}
bool hasWon() => _prize==_chosen;
String toString() {
String res="Prize is behind door $_prize";
if(_chosen!=null) res+=", player has chosen door $_chosen";
if(_open!=null) res+=", door $_open is open";
return res;
}
}
void play(int count, bool swap) {
int wins=0;
for(int i=0;i<count;i++) {
Game game=new Game();
game.choose(rand(3));
game.reveal();
if(swap)
game.change();
if(game.hasWon())
wins++;
}
String withWithout=swap?"with":"without";
double percent=(wins*100.0)/count;
print("playing $withWithout switching won $percent%");
}
test() {
for(int i=0;i<5;i++) {
Game g=new Game();
g.choose(i%3);
g.reveal();
print(g);
g.change();
print(g);
print("win==${g.hasWon()}");
}
}
main() {
play(10000,false);
play(10000,true);
} | 559Monty Hall problem
| 18dart
| u02vs |
modInv :: Int -> Int -> Maybe Int
modInv a m
| 1 == g = Just (mkPos i)
| otherwise = Nothing
where
(i, _, g) = gcdExt a m
mkPos x
| x < 0 = x + m
| otherwise = x
gcdExt :: Int -> Int -> (Int, Int, Int)
gcdExt a 0 = (1, 0, a)
gcdExt a b =
let (q, r) = a `quotRem` b
(s, t, g) = gcdExt b r
in (t, s - q * t, g)
main :: IO ()
main = mapM_ print [2 `modInv` 4, 42 `modInv` 2017] | 556Modular inverse
| 8haskell
| v052k |
import Control.Monad
import System.Random
getPi throws = do
results <- replicateM throws one_trial
return (4 * fromIntegral (sum results) / fromIntegral throws)
where
one_trial = do
rand_x <- randomRIO (-1, 1)
rand_y <- randomRIO (-1, 1)
let dist :: Double
dist = sqrt (rand_x * rand_x + rand_y * rand_y)
return (if dist < 1 then 1 else 0) | 557Monte Carlo methods
| 8haskell
| me9yf |
{
my @cache;
use bigint;
sub mfact {
my ($s, $n) = @_;
return 1 if $n <= 0;
$cache[$s][$n] //= $n * mfact($s, $n - $s);
}
}
for my $s (1 .. 10) {
print "step=$s: ";
print join(" ", map(mfact($s, $_), 1 .. 10)), "\n";
} | 552Multifactorial
| 2perl
| 84t0w |
class Integer
def ordinalize
num = self.abs
ordinal = if (11..13).include?(num % 100)
else
case num % 10
when 1;
when 2;
when 3;
else
end
end
end
end
[(0..25),(250..265),(1000..1025)].each{|r| puts r.map(&:ordinalize).join(); puts} | 540N'th
| 14ruby
| suvqw |
var str="broood"
var number:[Int]=[1,17,15,0,0,5] | 550Move-to-front algorithm
| 17swift
| ya56e |
System.out.println(BigInteger.valueOf(42).modInverse(BigInteger.valueOf(2017))); | 556Modular inverse
| 9java
| ya96g |
(let [size 12
trange (range 1 (inc size))
fmt-width (+ (.length (str (* size size))) 1)
fmt-str (partial format (str "%" fmt-width "s"))
fmt-dec (partial format (str "% " fmt-width "d"))]
(doseq [s (cons
(apply str (fmt-str " ") (map #(fmt-dec %) trange))
(for [i trange]
(apply str (fmt-dec i) (map #(fmt-str (str %))
(map #(if (>= % i) (* i %) " ")
(for [j trange] j))))))]
(println s))) | 560Multiplication tables
| 6clojure
| svwqr |
fn nth(num: isize) -> String {
format!("{}{}", num, match (num% 10, num% 100) {
(1, 11) | (2, 12) | (3, 13) => "th",
(1, _) => "st",
(2, _) => "nd",
(3, _) => "rd",
_ => "th",
})
}
fn main() {
let ranges = [(0, 26), (250, 266), (1000, 1026)];
for &(s, e) in &ranges {
println!("[{}, {}):", s, e);
for i in s..e {
print!("{}, ", nth(i));
}
println!();
}
} | 540N'th
| 15rust
| 05usl |
public class MC {
public static void main(String[] args) {
System.out.println(getPi(10000));
System.out.println(getPi(100000));
System.out.println(getPi(1000000));
System.out.println(getPi(10000000));
System.out.println(getPi(100000000));
}
public static double getPi(int numThrows){
int inCircle= 0;
for(int i= 0;i < numThrows;i++){ | 557Monte Carlo methods
| 9java
| fhtdv |
var modInverse = function(a, b) {
a %= b;
for (var x = 1; x < b; x++) {
if ((a*x)%b == 1) {
return x;
}
}
} | 556Modular inverse
| 10javascript
| 2sulr |
object Nth extends App {
def abbrevNumber(i: Int) = print(s"$i${ordinalAbbrev(i)} ")
def ordinalAbbrev(n: Int) = {
val ans = "th" | 540N'th
| 16scala
| irgox |
function mcpi(n) {
var x, y, m = 0;
for (var i = 0; i < n; i += 1) {
x = Math.random();
y = Math.random();
if (x * x + y * y < 1) {
m += 1;
}
}
return 4 * m / n;
}
console.log(mcpi(1000));
console.log(mcpi(10000));
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(10000000)); | 557Monte Carlo methods
| 10javascript
| yam6r |
null | 556Modular inverse
| 11kotlin
| fhzdo |
>>> from functools import reduce
>>> from operator import mul
>>> def mfac(n, m): return reduce(mul, range(n, 0, -m))
>>> for m in range(1, 11): print(% (m, [mfac(n, m) for n in range(1, 11)]))
1: [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
2: [1, 2, 3, 8, 15, 48, 105, 384, 945, 3840]
3: [1, 2, 3, 4, 10, 18, 28, 80, 162, 280]
4: [1, 2, 3, 4, 5, 12, 21, 32, 45, 120]
5: [1, 2, 3, 4, 5, 6, 14, 24, 36, 50]
6: [1, 2, 3, 4, 5, 6, 7, 16, 27, 40]
7: [1, 2, 3, 4, 5, 6, 7, 8, 18, 30]
8: [1, 2, 3, 4, 5, 6, 7, 8, 9, 20]
9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
10: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> | 552Multifactorial
| 3python
| ogz81 |
null | 557Monte Carlo methods
| 11kotlin
| 84o0q |
null | 558Morse code
| 0go
| rdrgm |
multifactorial=function(x,n){
if(x<=n+1){
return(x)
}else{
return(x*multifactorial(x-n,n))
}
} | 552Multifactorial
| 13r
| qvnxs |
import System.IO
import MorseCode
import MorsePlaySox
main = do
hSetBuffering stdin NoBuffering
text <- getContents
play $ toMorse text | 558Morse code
| 8haskell
| 050s7 |
SELECT level card,
to_char(to_date(level,'j'),'fmjth') ord
FROM dual
CONNECT BY level <= 15;
SELECT to_char(to_date(5373485,'j'),'fmjth')
FROM dual; | 540N'th
| 19sql
| fhjdi |
function MonteCarlo ( n_throws )
math.randomseed( os.time() )
n_inside = 0
for i = 1, n_throws do
if math.random()^2 + math.random()^2 <= 1.0 then
n_inside = n_inside + 1
end
end
return 4 * n_inside / n_throws
end
print( MonteCarlo( 10000 ) )
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 10000000 ) ) | 557Monte Carlo methods
| 1lua
| ogi8h |
import java.util.*;
public class MorseCode {
final static String[][] code = {
{"A", ".- "}, {"B", "-... "}, {"C", "-.-. "}, {"D", "-.. "},
{"E", ". "}, {"F", "..-. "}, {"G", "--. "}, {"H", ".... "},
{"I", ".. "}, {"J", ".--- "}, {"K", "-.- "}, {"L", ".-.. "},
{"M", "-- "}, {"N", "-. "}, {"O", "--- "}, {"P", ".--. "},
{"Q", "--.- "}, {"R", ".-. "}, {"S", "... "}, {"T", "- "},
{"U", "..- "}, {"V", "...- "}, {"W", ".- - "}, {"X", "-..- "},
{"Y", "-.-- "}, {"Z", "--.. "}, {"0", "----- "}, {"1", ".---- "},
{"2", "..--- "}, {"3", "...-- "}, {"4", "....- "}, {"5", "..... "},
{"6", "-.... "}, {"7", "--... "}, {"8", "---.. "}, {"9", "----. "},
{"'", ".----. "}, {":", "---... "}, {",", "--..-- "}, {"-", "-....- "},
{"(", "-.--.- "}, {".", ".-.-.- "}, {"?", "..--.. "}, {";", "-.-.-. "},
{"/", "-..-. "}, {"-", "..--.- "}, {")", "---.. "}, {"=", "-...- "},
{"@", ".--.-. "}, {"\"", ".-..-."}, {"+", ".-.-. "}, {" ", "/"}}; | 558Morse code
| 9java
| a9a1y |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
games := 100000
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var switcherWins, keeperWins, shown int
for i := 0; i < games; i++ {
doors := []int{0, 0, 0}
doors[r.Intn(3)] = 1 | 559Monty Hall problem
| 0go
| fjnd0 |
def multifact(n, d)
n.step(1, -d).inject(:* )
end
(1..5).each {|d| puts \t} | 552Multifactorial
| 14ruby
| n76it |
var globalAudioContext = new webkitAudioContext();
function morsecode(text, unit, freq) {
'use strict'; | 558Morse code
| 10javascript
| susqz |
import System.Random (StdGen, getStdGen, randomR)
trials :: Int
trials = 10000
data Door = Car | Goat deriving Eq
play :: Bool -> StdGen -> (Door, StdGen)
play switch g = (prize, new_g)
where (n, new_g) = randomR (0, 2) g
d1 = [Car, Goat, Goat] !! n
prize = case switch of
False -> d1
True -> case d1 of
Car -> Goat
Goat -> Car
cars :: Int -> Bool -> StdGen -> (Int, StdGen)
cars n switch g = f n (0, g)
where f 0 (cs, g) = (cs, g)
f n (cs, g) = f (n - 1) (cs + result, new_g)
where result = case prize of Car -> 1; Goat -> 0
(prize, new_g) = play switch g
main = do
g <- getStdGen
let (switch, g2) = cars trials True g
(stay, _) = cars trials False g2
putStrLn $ msg "switch" switch
putStrLn $ msg "stay" stay
where msg strat n = "The " ++ strat ++ " strategy succeeds " ++
percent n ++ "% of the time."
percent n = show $ round $
100 * (fromIntegral n) / (fromIntegral trials) | 559Monty Hall problem
| 8haskell
| 4ou5s |
use bigint; say 42->bmodinv(2017);
use Math::ModInt qw/mod/; say mod(42, 2017)->inverse->residue;
use Math::Pari qw/PARI lift/; say lift PARI "Mod(1/42,2017)";
use Math::GMP qw/:constant/; say 42->bmodinv(2017);
use ntheory qw/invmod/; say invmod(42, 2017); | 556Modular inverse
| 2perl
| hzbjl |
fn multifactorial(n: i32, deg: i32) -> i32 {
if n < 1 {
1
} else {
n * multifactorial(n - deg, deg)
}
}
fn main() {
for i in 1..6 {
for j in 1..11 {
print!("{} ", multifactorial(j, i));
}
println!("");
}
} | 552Multifactorial
| 15rust
| djyny |
func addSuffix(n:Int) -> String {
if n% 100 / 10 == 1 {
return "th"
}
switch n% 10 {
case 1:
return "st"
case 2:
return "nd"
case 3:
return "rd"
default:
return "th"
}
}
for i in 0...25 {
print("\(i)\(addSuffix(i)) ")
}
println()
for i in 250...265 {
print("\(i)\(addSuffix(i)) ")
}
println()
for i in 1000...1025 {
print("\(i)\(addSuffix(i)) ")
}
println() | 540N'th
| 17swift
| qv2xg |
def multiFact(n : BigInt, degree : BigInt) = (n to 1 by -degree).product
for{
degree <- 1 to 5
str = (1 to 10).map(n => multiFact(n, degree)).mkString(" ")
} println(s"Degree $degree: $str") | 552Multifactorial
| 16scala
| zbctr |
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioSystem
val morseCode = hashMapOf(
'a' to ".-", 'b' to "-...", 'c' to "-.-.",
'd' to "-..", 'e' to ".", 'f' to "..-.",
'g' to "--.", 'h' to "....", 'i' to "..",
'j' to ".---", 'k' to "-.-", 'l' to ".-..",
'm' to "--", 'n' to "-.", 'o' to "---",
'p' to ".--.", 'q' to "--.-", 'r' to ".-.",
's' to "...", 't' to "-", 'u' to "..-",
'v' to "...-", 'w' to ".--", 'x' to "-..-",
'y' to "-.--", 'z' to "--..",
'0' to ".....", '1' to "-....", '2' to "--...",
'3' to "---..", '4' to "----.", '5' to "-----",
'6' to ".----", '7' to "..---", '8' to "...--",
'9' to "....-",
' ' to "/", ',' to "--..--", '!' to "-.-.--",
'"' to ".-..-.", '.' to ".-.-.-", '?' to "..--..",
'\'' to ".----.", '/' to "-..-.", '-' to "-....-",
'(' to "-.--.-", ')' to "-.--.-"
)
val symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '/' to 1000)
fun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) }
.fold("") { acc, ch -> acc + morseCode[ch]!! }
fun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) }
fun beep(durationInMs: Int) {
val soundBuffer = ByteArray(durationInMs * 8)
for ((i, _) in soundBuffer.withIndex()) {
soundBuffer[i] = (Math.sin(i / 8.0 * 2.0 * Math.PI) * 80.0).toByte()
}
val audioFormat = AudioFormat(
8000F,
8,
1,
true,
false
)
with (AudioSystem.getSourceDataLine(audioFormat)!!) {
open(audioFormat)
start()
write(soundBuffer, 0, soundBuffer.size)
drain()
close()
}
}
fun main(args: Array<String>) {
args.forEach {
playMorseCode(toMorseCode(it.toLowerCase()))
}
} | 558Morse code
| 11kotlin
| hzhj3 |
<?php
function invmod($a,$n){
if ($n < 0) $n = -$n;
if ($a < 0) $a = $n - (-$a % $n);
$t = 0; $nt = 1; $r = $n; $nr = $a % $n;
while ($nr != 0) {
$quot= intval($r/$nr);
$tmp = $nt; $nt = $t - $quot*$nt; $t = $tmp;
$tmp = $nr; $nr = $r - $quot*$nr; $r = $tmp;
}
if ($r > 1) return -1;
if ($t < 0) $t += $n;
return $t;
}
printf(, invmod(42, 2017));
?> | 556Modular inverse
| 12php
| zb6t1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.