code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
my ($board_size, @occupied, @past, @solutions);
sub try_column {
my ($depth, @diag) = shift;
if ($depth == $board_size) {
push @solutions, "@past\n";
return;
}
$
for (0 .. $
$diag[ $past[$_] + $depth - $_ ] = 1;
$diag[ $past[$_] - $depth + $_ ] = 1;
}
for my $row (0 .. $board_size - 1) {
next if $occupied[$row] || $diag[$row];
push @past, $row;
$occupied[$row] = 1;
try_column($depth + 1);
$occupied[$row] = 0;
pop @past;
}
}
$board_size = 12;
try_column(0);
print "total " . @solutions . " solutions\n"; | 543N-queens problem
| 2perl
| 5oqu2 |
null | 540N'th
| 20typescript
| meayd |
local M = {} | 558Morse code
| 1lua
| k3kh2 |
import java.util.Random;
public class Monty{
public static void main(String[] args){
int switchWins = 0;
int stayWins = 0;
Random gen = new Random();
for(int plays = 0;plays < 32768;plays++ ){
int[] doors = {0,0,0}; | 559Monty Hall problem
| 9java
| cwm9h |
func multiFactorial(_ n: Int, k: Int) -> Int {
return stride(from: n, to: 0, by: -k).reduce(1, *)
}
let multis = (1...5).map({degree in
(1...10).map({member in
multiFactorial(member, k: degree)
})
})
for (i, degree) in multis.enumerated() {
print("Degree \(i + 1): \(degree)")
} | 552Multifactorial
| 17swift
| ir3o0 |
<html>
<head>
<title>
n x n Queen solving program
</title>
</head>
<body>
<?php
echo ;
$boardX = $_POST['boardX'];
$boardY = $_POST['boardX'];
function rotateBoard($p, $boardX) {
$a=0;
while ($a < count($p)) {
$b = strlen(decbin($p[$a]))-1;
$tmp[$b] = 1 << ($boardX - $a - 1);
++$a;
}
ksort($tmp);
return $tmp;
}
function findRotation($p, $boardX,$solutions){
$tmp = rotateBoard($p,$boardX);
if (in_array($tmp,$solutions)) {}
else {$solutions[] = $tmp;}
$tmp = rotateBoard($tmp,$boardX);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
$tmp = rotateBoard($tmp,$boardX);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
$tmp = array_reverse($p);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
$tmp = rotateBoard($tmp,$boardX);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
$tmp = rotateBoard($tmp,$boardX);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
$tmp = rotateBoard($tmp,$boardX);
if (in_array($tmp,$solutions)){}
else {$solutions[] = $tmp;}
return $solutions;
}
function renderBoard($p,$boardX) {
$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAABmJLR0QA/wD/AP+gvaeTAAAGFUlEQVRYhe2YXWibVRjHf2lqP9JmaRi4YW1IalY3rbZsaddMgsquBm676b6KyNDhLiaUeSEMvPNCcNuNyJjgLiboCnoxKFlv6lcHy7AtMhhaWTVZWhisjDTEtEuW5PHiPWnfvH2TvNk6vekfDm/O+Z/zPP/3PM/5eAMb2MAG/nfYn4LNVuBj4ENgB/Ar8Ogp+KkJbwLfqvKGgbMBPwKiK+Oq3aqNdcebQEEnqAC8ruO7KBVcLF012KiKuhpFv0/prNlU239qw0x0pdBJFXt30NJDjx9Uu1Ub1TSYdq4UutcNfI61oW0Bflb8T6quRzUbNafPFdbm4zcmTucV91kZO18o/osy/GeKnzcRVFWDMT2shO4X4IL6/UqZPv2GpxHFcReUvVo1lMAYunKh+UTxeeB5A/cMkFF8RtX1eF6NE2XHTIN+ltekoHGmf0HLqe9V3Qb8ZWK4Xjf+HQP3KtCgfjeouh7v6PzWsxZ6f98De1kbjbIovumoCfcp2gzkgb8p3cJOUjpTJ3WcTfXPq/Gfmtge1Y01RaV9+jv1fAsYMnAu3XgfENJxfUoU6tmn40Kqf9Gvi1IMKX96/zWJnlLP4i7wrIEvzkQeeFfXvltnt07Vi3iX1RcyzuSzrO46ev81YS+rYcqjbUVFfIl2CSryS4ATcKCF3biQHIpf0rU/UnaKuMLqAhXlv2a4Dc4FOKi4bwyiBTgBvGYyRlT7CUPbI1b334MmY9zlhFVKjwQQ09ULaDNTNKYPbx54j9L81aNP8XldW3G8W9kt6LiY8m8Ksy1Hj0mgA+3eXYeWd2eBRkpf2A4MoO3JOYPdHPA2sMtgu07ZOavsFnegvPL72PiItWEroB0axtwtmPStxOeUHbNxH1USVe1qOm3SVkA7NIwX+1phU3YKJpyZX8swW4y1FOMsVotG1UUI1mbrH9ZeL/UQi3b0C7dS/2W0LbIsqi1E0K6PL5oRdrudHTt22Px+Pz6fD6/XS3NzM21tbSt9FhcXWVpaIhqN2mKxGLOzs8zMzJDP581MQukHw2OLPgt8VRQZDAbZv38/wWCQnTt30tKyGoRUKsWDBw/IZrOkUimcTicNDQ1s3rwZp9O50i+dTjM9Pc2NGzcIh8NEIhH9S3xuQVNV2IArp06dkoWFBRERefjwoUxMTMi5c+fk8OHD0tPTIy6Xq2Keulwu6enpkSNHjsj58+dlYmJCMpmMiIgsLCzIxYsXBe1UfNIFvoL6M2fO/Hn58uXC4OCgtLa2PsniXClOp1MGBwfl0qVLhdOnT/+BtcjX9FYe4Pe+vj6Hy+Vat9lIJpMyOTm5BLwExNfL7gpCodAFeQoIhUIXqntfhaVwFHH9+nXp7+8vuFyuWv8vKYtkMlmYnJwse+F/Urzi9/ulqanJ6gFhqTQ1NeW7u7sF6Fx3xd3d3bdERNLptITDYRkeHpZgMCgOh6MmkQ6HQ/bs2SPDw8MSDoclnU6LiMju3buvlHG9BlYX1F5gfGhoiEAgwL59+9i+fTsAuVyOWCxGPB4nHo+TSCTIZrMkEgncbjeNjY243W46OjrweDx4vV7q67WsnJmZYWxsjGvXrjE+Pm5Zj1XRX3d2dg7Nz8/bs9ksAFu2bGHXrl0EAgG2bduG1+vF4/HgdDrZtGkTdrudXC5HKpUilUpx9+5dYrEYd+7cYXp6mqmpKe7fvw9AQ0MDXV1d3L59+2Xgd4uaKqO3t/cnEZFkMikjIyNy9OhRaW9vf6Jcbm9vl2PHjsnIyIgkk0kRETl06NAHVvRYnenA8ePHJ4PBIAcOHGDr1q0AxONxbt68yezsLNFolLm5ORKJBMvLy6TTaVpaWmhubl5JD5/Ph9/vZ2BgAI/HA8C9e/cYHR3l6tWry2NjY88Bi+slGqAHOFVXVxfq7e3tGhgYqAsGgwQCAfH5fLbGxsaqBjKZDNFoVKampmyRSIRIJFK4devWn4VC4TpwEfjNipDHPdlagADaf3X9NpvthY6Ojk6Px+Mq3vLsdjv5fJ7FxUWWl5eJx+OJubm5mIjMon1O/Yr2N0G6VufrdhwrtAJtaN9+bWihzqB9pNYsbgMbeAz8C3N/JQD4H5KCAAAAAElFTkSuQmCC';
echo ;
for ($y = 0; $y < $boardX; ++$y) {
echo '<tr>';
for ($x = 0; $x < $boardX; ++$x){
if (($x+$y) & 1) { $cellCol = '
else {$cellCol = '
if ($p[$y] == 1 << $x) { echo .$cellCol..$img.;}
else { echo .$cellCol.;}
}
echo '<tr>';
}
echo '<tr></tr></table> ';
}
function pc_next_permutation($p) {
$size = count($p) - 1;
for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { }
if ($i == -1) { return false; }
for ($j = $size; $p[$j] <= $p[$i]; --$j) { }
$tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp;
for (++$i, $j = $size; $i < $j; ++$i, --$j)
{ $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; }
return $p;
}
function checkBoard($p,$boardX) {
$a = 0;
while ($a < count($p)) {
$b = 1;
while ($b < ($boardX - $a)){
$x = $p[$a+$b] << $b;
$y = $p[$a+$b] >> $b;
if ($p[$a] == $x | $p[$a] == $y) {
return false;
}
++$b;
}
++$a;
}
return true;
}
if (isset($_POST['process']) && isset($_POST['boardX']))
{
for ($x = 0; $x < $boardX; ++$x){
$row[$x] = 1 << $x;
}
$solcount = 0;
$solutions = array();
while ($row != false) {
if (checkBoard($row,$boardX)){
if(!in_array($row,$solutions)){
$solutions[] = $row;
renderBoard($row,$boardX);
$solutions = findRotation($row,$boardX,$solutions);
++$solcount;
}
}
$row = pc_next_permutation($row);
}
echo .$boardX..$solcount..count($solutions).;
}
echo <<<_END
<form name= action= method=>
    Number of columns/rows <select name= />
<option value=>One</option>
<option value=>Two</option>
<option value=>Three</option>
<option value= >Four</option>
<option value=>Five</option>
<option value=>Six</option>
<option value=>Seven</option>
<option value= selected=>Eight</option>
<option value=>Nine</option>
<option value=>Ten</option>
</select>
<input type= name= value= />
 <input type= value= />
</form>
_END;
?>
</body>
</html> | 543N-queens problem
| 12php
| ogv85 |
sub pi {
my $nthrows = shift;
my $inside = 0;
foreach (1 .. $nthrows) {
my $x = rand() * 2 - 1;
my $y = rand() * 2 - 1;
if (sqrt($x*$x + $y*$y) < 1) {
$inside++;
}
}
return 4 * $inside / $nthrows;
}
printf "%9d:%07f\n", $_, pi($_) for 10**4, 10**6; | 557Monte Carlo methods
| 2perl
| 4ig5d |
function montyhall(tests, doors) {
'use strict';
tests = tests ? tests : 1000;
doors = doors ? doors : 3;
var prizeDoor, chosenDoor, shownDoor, switchDoor, chosenWins = 0, switchWins = 0; | 559Monty Hall problem
| 10javascript
| 58vur |
<?
$loop = 1000000;
$count = 0;
for ($i=0; $i<$loop; $i++) {
$x = rand() / getrandmax();
$y = rand() / getrandmax();
if(($x*$x) + ($y*$y)<=1) $count++;
}
echo .number_format($loop)..number_format($count)..($count/$loop*4);
?> | 557Monte Carlo methods
| 12php
| irnov |
>>> def extended_gcd(aa, bb):
lastremainder, remainder = abs(aa), abs(bb)
x, lastx, y, lasty = 0, 1, 1, 0
while remainder:
lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
x, lastx = lastx - quotient*x, x
y, lasty = lasty - quotient*y, y
return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)
>>> def modinv(a, m):
g, x, y = extended_gcd(a, m)
if g != 1:
raise ValueError
return x% m
>>> modinv(42, 2017)
1969
>>> | 556Modular inverse
| 3python
| k3phf |
null | 559Monty Hall problem
| 11kotlin
| 3btz5 |
sub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 }
sub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }
foreach my $sequence (\&F, \&M) {
print join(' ', map $sequence->($_), 0 .. 19), "\n";
} | 542Mutual recursion
| 2perl
| u8qvr |
function playgame(player)
local car = math.random(3)
local pchoice = player.choice()
local function neither(a, b) | 559Monty Hall problem
| 1lua
| 6pz39 |
def extended_gcd(a, b)
last_remainder, remainder = a.abs, b.abs
x, last_x, y, last_y = 0, 1, 1, 0
while remainder!= 0
last_remainder, (quotient, remainder) = remainder, last_remainder.divmod(remainder)
x, last_x = last_x - quotient*x, x
y, last_y = last_y - quotient*y, y
end
return last_remainder, last_x * (a < 0? -1: 1)
end
def invmod(e, et)
g, x = extended_gcd(e, et)
if g!= 1
raise 'The maths are broken!'
end
x % et
end | 556Modular inverse
| 14ruby
| pyabh |
>>> import random, math
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
for q in [0,1]]) < 1
for p in xrange(throws)) / float(throws)
3.1520000000000001
>>> throws = 1000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
for q in [0,1]]) < 1
for p in xrange(throws)) / float(throws)
3.1396359999999999
>>> throws = 100000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
for q in [0,1]]) < 1
for p in xrange(throws)) / float(throws)
3.1415666400000002 | 557Monte Carlo methods
| 3python
| gnr4h |
fn mod_inv(a: isize, module: isize) -> isize {
let mut mn = (module, a);
let mut xy = (0, 1);
while mn.1!= 0 {
xy = (xy.1, xy.0 - (mn.0 / mn.1) * xy.1);
mn = (mn.1, mn.0% mn.1);
}
while xy.0 < 0 {
xy.0 += module;
}
xy.0
}
fn main() {
println!("{}", mod_inv(42, 2017))
} | 556Modular inverse
| 15rust
| 1mepu |
def gcdExt(u: Int, v: Int): (Int, Int, Int) = {
@tailrec
def aux(a: Int, b: Int, x: Int, y: Int, x1: Int, x2: Int, y1: Int, y2: Int): (Int, Int, Int) = {
if(b == 0) (x, y, a) else {
val (q, r) = (a / b, a % b)
aux(b, r, x2 - q * x1, y2 - q * y1, x, x1, y, y1)
}
}
aux(u, v, 1, 0, 0, 1, 1, 0)
}
def modInv(a: Int, m: Int): Option[Int] = {
val (i, j, g) = gcdExt(a, m)
if (g == 1) Option(if (i < 0) i + m else i) else Option.empty
} | 556Modular inverse
| 16scala
| wlqes |
<?php
function F($n)
{
if ( $n == 0 ) return 1;
return $n - M(F($n-1));
}
function M($n)
{
if ( $n == 0) return 0;
return $n - F(M($n-1));
}
$ra = array();
$rb = array();
for($i=0; $i < 20; $i++)
{
array_push($ra, F($i));
array_push($rb, M($i));
}
echo implode(, $ra) . ;
echo implode(, $rb) . ;
?> | 542Mutual recursion
| 12php
| 84v0m |
monteCarloPi <- function(samples) {
x <- runif(samples, -1, 1)
y <- runif(samples, -1, 1)
l <- sqrt(x*x + y*y)
return(4*sum(l<=1)/samples)
}
monteCarlo2Pi <- function(samples, group=100) {
lim <- ceiling(samples/group)
olim <- lim
c <- 0
while(lim > 0) {
x <- runif(group, -1, 1)
y <- runif(group, -1, 1)
l <- sqrt(x*x + y*y)
c <- c + sum(l <= 1)
lim <- lim - 1
}
return(4*c/(olim*group))
}
print(monteCarloPi(1e4))
print(monteCarloPi(1e5))
print(monteCarlo2Pi(1e7)) | 557Monte Carlo methods
| 13r
| v0u27 |
extension BinaryInteger {
@inlinable
public func modInv(_ mod: Self) -> Self {
var (m, n) = (mod, self)
var (x, y) = (Self(0), Self(1))
while n!= 0 {
(x, y) = (y, x - (m / n) * y)
(m, n) = (n, m% n)
}
while x < 0 {
x += mod
}
return x
}
}
print(42.modInv(2017)) | 556Modular inverse
| 17swift
| b61kd |
use Acme::AGMorse qw(SetMorseVals SendMorseMsg);
SetMorseVals(20,30,400);
SendMorseMsg('Hello World! abcdefg @\;');
exit; | 558Morse code
| 2perl
| zbztb |
def approx_pi(throws)
times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
4.0 * times_inside / throws
end
[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
puts % [n, approx_pi(n)]
end | 557Monte Carlo methods
| 14ruby
| 7fjri |
null | 556Modular inverse
| 20typescript
| djtn0 |
extern crate rand;
use rand::Rng;
use std::f64::consts::PI; | 557Monte Carlo methods
| 15rust
| jth72 |
object MonteCarlo {
private val random = new scala.util.Random
def nextThrow: Double = (random.nextDouble * 2.0) - 1.0
def insideCircle(pt: (Double, Double)): Boolean = pt match {
case (x, y) => (x * x) + (y * y) <= 1.0
}
def simulate(times: Int): Double = {
val inside = Iterator.tabulate (times) (_ => (nextThrow, nextThrow)) count insideCircle
inside.toDouble / times.toDouble * 4.0
}
def main(args: Array[String]): Unit = {
val sims = Seq(10000, 100000, 1000000, 10000000, 100000000)
sims.foreach { n =>
println(n+" simulations; pi estimation: "+ simulate(n))
}
}
} | 557Monte Carlo methods
| 16scala
| b6pk6 |
from itertools import permutations
n = 8
cols = range(n)
for vec in permutations(cols):
if n == len(set(vec[i]+i for i in cols)) \
== len(set(vec[i]-i for i in cols)):
print ( vec ) | 543N-queens problem
| 3python
| 4is5k |
use strict;
my $trials = 10000;
my $stay = 0;
my $switch = 0;
foreach (1 .. $trials)
{
my $prize = int(rand 3);
my $chosen = int(rand 3);
my $show;
do { $show = int(rand 3) } while $show == $chosen || $show == $prize;
$stay++ if $prize == $chosen;
$switch++ if $prize == 3 - $chosen - $show;
}
print "Stay win ratio " . (100.0 * $stay/$trials) . "\n";
print "Switch win ratio " . (100.0 * $switch/$trials) . "\n"; | 559Monty Hall problem
| 2perl
| p6kb0 |
package main
import (
"fmt"
)
func main() {
fmt.Print(" x |")
for i := 1; i <= 12; i++ {
fmt.Printf("%4d", i)
}
fmt.Print("\n---+")
for i := 1; i <= 12; i++ {
fmt.Print("----")
}
for j := 1; j <= 12; j++ {
fmt.Printf("\n%2d |", j)
for i := 1; i <= 12; i++ {
if i >= j {
fmt.Printf("%4d", i*j)
} else {
fmt.Print(" ")
}
}
}
fmt.Println("")
} | 560Multiplication tables
| 0go
| ma3yi |
import Foundation
func mcpi(sampleSize size:Int) -> Double {
var x = 0 as Double
var y = 0 as Double
var m = 0 as Double
for i in 0..<size {
x = Double(arc4random()) / Double(UINT32_MAX)
y = Double(arc4random()) / Double(UINT32_MAX)
if ((x * x) + (y * y) < 1) {
m += 1
}
}
return (4.0 * m) / Double(size)
}
println(mcpi(sampleSize: 100))
println(mcpi(sampleSize: 1000))
println(mcpi(sampleSize: 10000))
println(mcpi(sampleSize: 100000))
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000)) | 557Monte Carlo methods
| 17swift
| rd7gg |
def printMultTable = { size = 12 ->
assert size > 1 | 560Multiplication tables
| 7groovy
| thnfh |
queens <- function(n) {
a <- seq(n)
u <- rep(T, 2 * n - 1)
v <- rep(T, 2 * n - 1)
m <- NULL
aux <- function(i) {
if (i > n) {
m <<- cbind(m, a)
} else {
for (j in seq(i, n)) {
k <- a[[j]]
p <- i - k + n
q <- i + k - 1
if (u[[p]] && v[[q]]) {
u[[p]] <<- v[[q]] <<- F
a[[j]] <<- a[[i]]
a[[i]] <<- k
aux(i + 1)
u[[p]] <<- v[[q]] <<- T
a[[i]] <<- a[[j]]
a[[j]] <<- k
}
}
}
}
aux(1)
m
} | 543N-queens problem
| 13r
| 2selg |
<?php
function montyhall($iterations){
$switch_win = 0;
$stay_win = 0;
foreach (range(1, $iterations) as $i){
$doors = array(0, 0, 0);
$doors[array_rand($doors)] = 1;
$choice = array_rand($doors);
do {
$shown = array_rand($doors);
} while($shown == $choice || $doors[$shown] == 1);
$stay_win += $doors[$choice];
$switch_win += $doors[3 - $choice - $shown];
}
$stay_percentages = ($stay_win/$iterations)*100;
$switch_percentages = ($switch_win/$iterations)*100;
echo ;
echo ;
echo ;
}
montyhall(10000);
?> | 559Monty Hall problem
| 12php
| y1361 |
def F(n): return 1 if n == 0 else n - M(F(n-1))
def M(n): return 0 if n == 0 else n - F(M(n-1))
print ([ F(n) for n in range(20) ])
print ([ M(n) for n in range(20) ]) | 542Mutual recursion
| 3python
| 5osux |
import time, winsound
char2morse = {
: , .-..-.$...-..-'.----.(-.--.)-.--.-+.-.-.,--..----....-..-.-.-/-..-.0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.:---...;-.-.-.=-...-?..--..@.--.-.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--..[-.--.]-.--.-_..--.-",
}
e = 50
f = 1280
chargap = 1
wordgap = 7
def gap(n=1):
time.sleep(n * e / 1000)
off = gap
def on(n=1):
winsound.Beep(f, n * e)
def dit():
on(); off()
def dah():
on(3); off()
def bloop(n=3):
winsound.Beep(f
def windowsmorse(text):
for word in text.strip().upper().split():
for char in word:
for element in char2morse.get(char, '?'):
if element == '-':
dah()
elif element == '.':
dit()
else:
bloop()
gap(chargap)
gap(wordgap)
while True:
windowsmorse(input('A string to change into morse: ')) | 558Morse code
| 3python
| 3p3zc |
import Data.Maybe (fromMaybe, maybe)
mulTable :: [Int] -> [[Maybe Int]]
mulTable xs =
(Nothing: labels):
zipWith
(:)
labels
[[upperMul x y | y <- xs] | x <- xs]
where
labels = Just <$> xs
upperMul x y
| x > y = Nothing
| otherwise = Just (x * y)
main :: IO ()
main =
putStrLn . unlines $
showTable . mulTable
<$> [ [13 .. 20],
[1 .. 12],
[95 .. 100]
]
showTable :: [[Maybe Int]] -> String
showTable xs = unlines $ head rows: []: tail rows
where
w = succ $ (length . show) (fromMaybe 0 $ (last . last) xs)
gap = replicate w ' '
rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
rjust n c = (drop . length) <*> (replicate n c <>) | 560Multiplication tables
| 8haskell
| kz7h0 |
F <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))
M <- function(n) ifelse(n == 0, 0, n - F(M(n-1))) | 542Mutual recursion
| 13r
| lqece |
def n_queens(n)
if n == 1
return
elsif n < 4
puts
return
end
evens = (2..n).step(2).to_a
odds = (1..n).step(2).to_a
rem = n % 12
nums = evens
nums.rotate if rem == 3 or rem == 9
if rem == 8
odds = odds.each_slice(2).flat_map(&:reverse)
end
nums.concat(odds)
if rem == 2
nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)]
nums << nums.delete(5)
end
if rem == 3 or rem == 9
nums << nums.delete(1)
nums << nums.delete(3)
end
nums.map do |q|
a = Array.new(n,)
a[q-1] =
a*()
end
end
(1 .. 15).each {|n| puts ; puts n_queens(n); puts} | 543N-queens problem
| 14ruby
| rd8gs |
require 'win32/sound'
class MorseCode
MORSE = {
=> , .-..-.$...-..-'.----.(-.--.)-.--.-+.-.-.,--..----....-..-.-.-/-..-.0-----1.----2..---3...--4....-5.....6-....7--...8---..9----.:---...;-.-.-.=-...-?..--..@.--.-.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--..[-.--.]-.--.-_..--.-your message is
end
def send
@message.strip.upcase.split.each do |word|
word.each_char do |char|
send_char char
pause CHARGAP
print
end
pause WORDGAP
puts
end
end
private
def send_char(char)
MORSE[char].each_char do |code|
case code
when '.' then beep DIT
when '-' then beep DAH
end
pause CHARGAP
print code
end
end
def beep(ms)
::Win32::Sound.beep(FREQ, ms)
end
def pause(ms)
sleep(ms.to_f/1000.0)
end
end
MorseCode.new('sos').send
MorseCode.new('this is a test.').send | 558Morse code
| 14ruby
| yay6n |
'''
I could understand the explanation of the Monty Hall problem
but needed some more evidence
References:
http:
http:
http:
'''
from random import randrange
doors, iterations = 3,100000
def monty_hall(choice, switch=False, doorCount=doors):
door = [False]*doorCount
door[randrange(doorCount)] = True
chosen = door[choice]
unpicked = door
del unpicked[choice]
alternative = True in unpicked
if switch:
return alternative
else:
return chosen
print
print doors, , iterations,
print ,
print sum(monty_hall(randrange(3), switch=False)
for x in range(iterations)),
print , iterations,
print ,
print sum(monty_hall(randrange(3), switch=True)
for x in range(iterations)),
print , iterations, | 559Monty Hall problem
| 3python
| 1ybpc |
public class MultiplicationTable {
public static void main(String[] args) {
for (int i = 1; i <= 12; i++)
System.out.print("\t" + i);
System.out.println();
for (int i = 0; i < 100; i++)
System.out.print("-");
System.out.println();
for (int i = 1; i <= 12; i++) {
System.out.print(i + "|");
for(int j = 1; j <= 12; j++) {
System.out.print("\t");
if (j >= i)
System.out.print("\t" + i * j);
}
System.out.println();
}
}
} | 560Multiplication tables
| 9java
| 4ov58 |
null | 558Morse code
| 15rust
| memya |
<!DOCTYPE html PUBLIC "- | 560Multiplication tables
| 10javascript
| htrjh |
const N: usize = 8;
fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
if row == N {
*count += 1;
for r in board.iter() {
println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" "))
}
println!("");
return
}
for i in 0..N {
let mut ok: bool = true;
for j in 0..row {
if board[j][i]
|| i+j >= row && board[j][i+j-row]
|| i+row < N+j && board[j][i+row-j]
{ ok = false }
}
if ok {
board[row][i] = true;
try(&mut board, row+1, &mut count);
board[row][i] = false;
}
}
}
fn main() {
let mut board: [[bool; N]; N] = [[false; N]; N];
let mut count: i64 = 0;
try (&mut board, 0, &mut count);
println!("Found {} solutions", count)
} | 543N-queens problem
| 15rust
| 7forc |
def F(n)
n == 0? 1: n - M(F(n-1))
end
def M(n)
n == 0? 0: n - F(M(n-1))
end
p (Array.new(20) {|n| F(n) })
p (Array.new(20) {|n| M(n) }) | 542Mutual recursion
| 14ruby
| gn84q |
object MorseCode extends App {
private val code = Map(
('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
| 16scala
| lqlcq |
set.seed(19771025)
N <- 10000
true_answers <- sample(1:3, N, replace=TRUE)
host_opens <- 2 + (true_answers == 2)
other_door <- 2 + (true_answers != 2)
summary( other_door == true_answers )
summary( true_answers == 1)
random_switch <- other_door
random_switch[runif(N) >= .5] <- 1
summary(random_switch == true_answers)
N <- 10000
true_answers <- sample(1:3, N, replace=TRUE)
user_choice <- sample(1:3, N, replace=TRUE)
host_chooser <- function(user_prize) {
bad_choices <- unique(user_prize)
choices <- c(1:3)[-bad_choices]
if (length(choices) == 1) { return(choices)}
else { return(sample(choices,1))}
}
host_choice <- apply( X=cbind(true_answers,user_choice), FUN=host_chooser,MARGIN=1)
not_door <- function(x){ return( (1:3)[-x]) }
other_door <- apply( X = cbind(user_choice,host_choice), FUN=not_door, MARGIN=1)
summary( other_door == true_answers )
summary( true_answers == user_choice)
random_switch <- user_choice
change <- runif(N) >= .5
random_switch[change] <- other_door[change]
summary(random_switch == true_answers) | 559Monty Hall problem
| 13r
| ht7jj |
object NQueens {
private implicit class RichPair[T](
pair: (T,T))(
implicit num: Numeric[T]
) {
import num._
def safe(x: T, y: T): Boolean =
pair._1 - pair._2 != abs(x - y)
}
def solve(n: Int): Iterator[Seq[Int]] = {
(0 to n-1)
.permutations
.filter { v =>
(0 to n-1).forall { y =>
(y+1 to n-1).forall { x =>
(x,y).safe(v(x),v(y))
}
}
}
}
def main(args: Array[String]): Unit = {
val n = args.headOption.getOrElse("8").toInt
val (solns1, solns2) = solve(n).duplicate
solns1
.zipWithIndex
.foreach { case (soln, i) =>
Console.out.println(s"Solution #${i+1}")
output(n)(soln)
}
val n_solns = solns2.size
if (n_solns == 1) {
Console.out.println("Found 1 solution")
} else {
Console.out.println(s"Found $n_solns solutions")
}
}
def output(n: Int)(board: Seq[Int]): Unit = {
board.foreach { queen =>
val row =
"_|" * queen + "Q" + "|_" * (n-queen-1)
Console.out.println(row)
}
}
} | 543N-queens problem
| 16scala
| k3dhk |
fn f(n: u32) -> u32 {
match n {
0 => 1,
_ => n - m(f(n - 1))
}
}
fn m(n: u32) -> u32 {
match n {
0 => 0,
_ => n - f(m(n - 1))
}
}
fn main() {
for i in (0..20).map(f) {
print!("{} ", i);
}
println!("");
for i in (0..20).map(m) {
print!("{} ", i);
}
println!("")
} | 542Mutual recursion
| 15rust
| rdog5 |
null | 560Multiplication tables
| 11kotlin
| lxmcp |
n = 10_000
stay = switch = 0
n.times do
doors = [ :goat, :goat, :car ].shuffle
guess = rand(3)
begin shown = rand(3) end while shown == guess || doors[shown] == :car
if doors[guess] == :car
stay += 1
else
switch += 1
end
end
puts % (100.0 * stay / n)
puts % (100.0 * switch / n) | 559Monty Hall problem
| 14ruby
| e91ax |
def F(n:Int):Int =
if (n == 0) 1 else n - M(F(n-1))
def M(n:Int):Int =
if (n == 0) 0 else n - F(M(n-1))
println((0 until 20).map(F).mkString(", "))
println((0 until 20).map(M).mkString(", ")) | 542Mutual recursion
| 16scala
| hzdja |
extern crate rand;
use rand::Rng;
use rand::seq::SliceRandom;
#[derive(Clone, Copy, PartialEq)]
enum Prize {Goat , Car}
const GAMES: usize = 3_000_000;
fn main() {
let mut switch_wins = 0;
let mut rng = rand::thread_rng();
for _ in 0..GAMES {
let mut doors = [Prize::Goat; 3];
*doors.choose_mut(&mut rng).unwrap() = Prize::Car; | 559Monty Hall problem
| 15rust
| wcae4 |
import scala.util.Random
object MontyHallSimulation {
def main(args: Array[String]) {
val samples = if (args.size == 1 && (args(0) matches "\\d+")) args(0).toInt else 1000
val doors = Set(0, 1, 2)
var stayStrategyWins = 0
var switchStrategyWins = 0
1 to samples foreach { _ =>
val prizeDoor = Random shuffle doors head;
val choosenDoor = Random shuffle doors head;
val hostDoor = Random shuffle (doors - choosenDoor - prizeDoor) head;
val switchDoor = doors - choosenDoor - hostDoor head;
(choosenDoor, switchDoor) match {
case (`prizeDoor`, _) => stayStrategyWins += 1
case (_, `prizeDoor`) => switchStrategyWins += 1
}
}
def percent(n: Int) = n * 100 / samples
val report = """|%d simulations were ran.
|Staying won%d times (%d%%)
|Switching won%d times (%d%%)""".stripMargin
println(report
format (samples,
stayStrategyWins, percent(stayStrategyWins),
switchStrategyWins, percent(switchStrategyWins)))
}
} | 559Monty Hall problem
| 16scala
| svxqo |
io.write( " |" )
for i = 1, 12 do
io.write( string.format( "%#5d", i ) )
end
io.write( "\n", string.rep( "-", 12*5+4 ), "\n" )
for i = 1, 12 do
io.write( string.format( "%#2d |", i ) )
for j = 1, 12 do
if j < i then
io.write( " " )
else
io.write( string.format( "%#5d", i*j ) )
end
end
io.write( "\n" )
end | 560Multiplication tables
| 1lua
| 2q9l3 |
WITH RECURSIVE
positions(i) AS (
VALUES(0)
UNION SELECT ALL
i+1 FROM positions WHERE i < 63
),
solutions(board, n_queens) AS (
SELECT '----------------------------------------------------------------', CAST(0 AS BIGINT)
FROM positions
UNION
SELECT
substr(board, 1, i) || '*' || substr(board, i+2),n_queens + 1 AS n_queens
FROM positions AS ps, solutions
WHERE n_queens < 8
AND substr(board,1,i)!= '*'
AND NOT EXISTS (
SELECT 1 FROM positions WHERE
substr(board,i+1,1) = '*' AND
(
i% 8 = ps.i%8 OR
CAST(i / 8 AS INT) = CAST(ps.i / 8 AS INT) OR
CAST(i / 8 AS INT) + (i% 8) = CAST(ps.i / 8 AS INT) + (ps.i% 8) OR
CAST(i / 8 AS INT) - (i% 8) = CAST(ps.i / 8 AS INT) - (ps.i% 8)
)
LIMIT 1
)
ORDER BY n_queens DESC -- remove this when using Postgres (they don't support ORDER BY in CTEs)
)
SELECT board,n_queens FROM solutions WHERE n_queens = 8; | 543N-queens problem
| 19sql
| 1mzpg |
package main
import (
"fmt"
"math"
)
const MAXITER = 151
func minkowski(x float64) float64 {
if x > 1 || x < 0 {
return math.Floor(x) + minkowski(x-math.Floor(x))
}
p := uint64(x)
q := uint64(1)
r := p + 1
s := uint64(1)
d := 1.0
y := float64(p)
for {
d = d / 2
if y+d == y {
break
}
m := p + r
if m < 0 || p < 0 {
break
}
n := q + s
if n < 0 {
break
}
if x < float64(m)/float64(n) {
r = m
s = n
} else {
y = y + d
p = m
q = n
}
}
return y + d
}
func minkowskiInv(x float64) float64 {
if x > 1 || x < 0 {
return math.Floor(x) + minkowskiInv(x-math.Floor(x))
}
if x == 1 || x == 0 {
return x
}
contFrac := []uint32{0}
curr := uint32(0)
count := uint32(1)
i := 0
for {
x *= 2
if curr == 0 {
if x < 1 {
count++
} else {
i++
t := contFrac
contFrac = make([]uint32, i+1)
copy(contFrac, t)
contFrac[i-1] = count
count = 1
curr = 1
x--
}
} else {
if x > 1 {
count++
x--
} else {
i++
t := contFrac
contFrac = make([]uint32, i+1)
copy(contFrac, t)
contFrac[i-1] = count
count = 1
curr = 0
}
}
if x == math.Floor(x) {
contFrac[i] = count
break
}
if i == MAXITER {
break
}
}
ret := 1.0 / float64(contFrac[i])
for j := i - 1; j >= 0; j-- {
ret = float64(contFrac[j]) + 1.0/ret
}
return 1.0 / ret
}
func main() {
fmt.Printf("%19.16f%19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)
fmt.Printf("%19.16f%19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)
fmt.Printf("%19.16f%19.16f\n", minkowski(minkowskiInv(0.718281828)),
minkowskiInv(minkowski(0.1213141516171819)))
} | 561Minkowski question-mark function
| 0go
| giv4n |
unsigned digit_sum(unsigned n) {
unsigned sum = 0;
do { sum += n % 10; }
while(n /= 10);
return sum;
}
unsigned a131382(unsigned n) {
unsigned m;
for (m = 1; n != digit_sum(m*n); m++);
return m;
}
int main() {
unsigned n;
for (n = 1; n <= 70; n++) {
printf(, a131382(n));
if (n % 10 == 0) printf();
}
return 0;
} | 562Minimum multiple of m where digital sum equals m
| 5c
| vsm2o |
import Data.Tree
import Data.Ratio
import Data.List
intervalTree :: (a -> a -> a) -> (a, a) -> Tree a
intervalTree node = unfoldTree $
\(a, b) -> let m = node a b in (m, [(a,m), (m,b)])
Node a _ ==> Node b [] = const b
Node a [] ==> Node b _ = const b
Node a [l1, r1] ==> Node b [l2, r2] =
\x -> case x `compare` a of
LT -> (l1 ==> l2) x
EQ -> b
GT -> (r1 ==> r2) x
mirror :: Num a => Tree a -> Tree a
mirror t = Node 0 [reflect (negate <$> t), t]
where
reflect (Node a [l,r]) = Node a [reflect r, reflect l]
sternBrocot :: Tree Rational
sternBrocot = toRatio <$> intervalTree mediant ((0,1), (1,0))
where
mediant (p, q) (r, s) = (p + r, q + s)
toRatio (p, q) = p % q
minkowski :: Tree Rational
minkowski = toRatio <$> intervalTree mean ((0,1), (1,0))
mean (p, q) (1, 0) = (p+1, q)
mean (p, q) (r, s) = (p*s + q*r, 2*q*s)
questionMark, invQuestionMark :: Rational -> Rational
questionMark = mirror sternBrocot ==> mirror minkowski
invQuestionMark = mirror minkowski ==> mirror sternBrocot
sternBrocotF :: Tree Double
sternBrocotF = mirror $ fromRational <$> sternBrocot
minkowskiF :: Tree Double
minkowskiF = mirror $ intervalTree mean (0, 1/0)
where
mean a b | isInfinite b = a + 1
| otherwise = (a + b) / 2
questionMarkF, invQuestionMarkF :: Double -> Double
questionMarkF = sternBrocotF ==> minkowskiF
invQuestionMarkF = minkowskiF ==> sternBrocotF | 561Minkowski question-mark function
| 8haskell
| sveqk |
import Foundation
func montyHall(doors: Int = 3, guess: Int, switch: Bool) -> Bool {
guard doors > 2, guess > 0, guess <= doors else { fatalError() }
let winningDoor = Int.random(in: 1...doors)
return winningDoor == guess?!`switch`: `switch`
}
var switchResults = [Bool]()
for _ in 0..<1_000 {
let guess = Int.random(in: 1...3)
let wasRight = montyHall(guess: guess, switch: true)
switchResults.append(wasRight)
}
let switchWins = switchResults.filter({ $0 }).count
print("Switching would've won \((Double(switchWins) / Double(switchResults.count)) * 100)% of games")
print("Not switching would've won \(((Double(switchResults.count - switchWins)) / Double(switchResults.count)) * 100)% of games") | 559Monty Hall problem
| 17swift
| amp1i |
package main
import (
"fmt"
"math"
"math/rand"
"strings"
"time"
)
func rng(modifier func(x float64) float64) float64 {
for {
r1 := rand.Float64()
r2 := rand.Float64()
if r2 < modifier(r1) {
return r1
}
}
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
rand.Seed(time.Now().UnixNano())
modifier := func(x float64) float64 {
if x < 0.5 {
return 2 * (0.5 - x)
}
return 2 * (x - 0.5)
}
const (
N = 100000
NUM_BINS = 20
HIST_CHAR = ""
HIST_CHAR_SIZE = 125
)
bins := make([]int, NUM_BINS) | 563Modified random distribution
| 0go
| e9ha6 |
import System.Random
import Data.List
import Text.Printf
modify :: Ord a => (a -> a) -> [a] -> [a]
modify f = foldMap test . pairs
where
pairs lst = zip lst (tail lst)
test (r1, r2) = if r2 < f r1 then [r1] else []
vShape x = if x < 0.5 then 2*(0.5-x) else 2*(x-0.5)
hist b lst = zip [0,b..] res
where
res = (`div` sum counts) . (*300) <$> counts
counts = map length $ group $
sort $ floor . (/b) <$> lst
showHist h = foldMap mkLine h
where
mkLine (b,n) = printf "%.2f\t%s%d%%\n" b (replicate n '') n | 563Modified random distribution
| 8haskell
| 3bizj |
struct ModularArithmetic {
int value;
int modulus;
};
struct ModularArithmetic make(const int value, const int modulus) {
struct ModularArithmetic r = { value % modulus, modulus };
return r;
}
struct ModularArithmetic add(const struct ModularArithmetic a, const struct ModularArithmetic b) {
return make(a.value + b.value, a.modulus);
}
struct ModularArithmetic addi(const struct ModularArithmetic a, const int v) {
return make(a.value + v, a.modulus);
}
struct ModularArithmetic mul(const struct ModularArithmetic a, const struct ModularArithmetic b) {
return make(a.value * b.value, a.modulus);
}
struct ModularArithmetic pow(const struct ModularArithmetic b, int pow) {
struct ModularArithmetic r = make(1, b.modulus);
while (pow-- > 0) {
r = mul(r, b);
}
return r;
}
void print(const struct ModularArithmetic v) {
printf(, v.value, v.modulus);
}
struct ModularArithmetic f(const struct ModularArithmetic x) {
return addi(add(pow(x, 100), x), 1);
}
int main() {
struct ModularArithmetic input = make(10, 13);
struct ModularArithmetic output = f(input);
printf();
print(input);
printf();
print(output);
printf();
return 0;
} | 564Modular arithmetic
| 5c
| madys |
let maxn = 31
func nq(n: Int) -> Int {
var cols = Array(repeating: 0, count: maxn)
var diagl = Array(repeating: 0, count: maxn)
var diagr = Array(repeating: 0, count: maxn)
var posibs = Array(repeating: 0, count: maxn)
var num = 0
for q0 in 0...n-3 {
for q1 in q0+2...n-1 {
let bit0: Int = 1<<q0
let bit1: Int = 1<<q1
var d: Int = 0
cols[0] = bit0 | bit1 | (-1<<n)
diagl[0] = (bit0<<1|bit1)<<1
diagr[0] = (bit0>>1|bit1)>>1
var posib: Int = ~(cols[0] | diagl[0] | diagr[0])
while (d >= 0) {
while(posib!= 0) {
let bit: Int = posib & -posib
let ncols: Int = cols[d] | bit
let ndiagl: Int = (diagl[d] | bit) << 1;
let ndiagr: Int = (diagr[d] | bit) >> 1;
let nposib: Int = ~(ncols | ndiagl | ndiagr);
posib^=bit
num += (ncols == -1? 1: 0)
if (nposib!= 0){
if(posib!= 0) {
posibs[d] = posib
d += 1
}
cols[d] = ncols
diagl[d] = ndiagl
diagr[d] = ndiagr
posib = nposib
}
}
d -= 1
posib = d<0? n: posibs[d]
}
}
}
return num*2
}
if(CommandLine.arguments.count == 2) {
let board_size: Int = Int(CommandLine.arguments[1])!
print ("Number of solutions for board size \(board_size) is: \(nq(n:board_size))")
} else {
print("Usage: 8q <n>")
} | 543N-queens problem
| 17swift
| gn049 |
use strict;
use warnings;
use feature 'say';
use POSIX qw(floor);
my $MAXITER = 50;
sub minkowski {
my($x) = @_;
return floor($x) + minkowski( $x - floor($x) ) if $x > 1 || $x < 0 ;
my $y = my $p = floor($x);
my ($q,$s,$d) = (1,1,1);
my $r = $p + 1;
while () {
last if ( $y + ($d /= 2) == $y ) or
( my $m = $p + $r) < 0 or
( my $n = $q + $s) < 0;
$x < $m/$n ? ($r,$s) = ($m, $n) : ($y += $d and ($p,$q) = ($m, $n) );
}
return $y + $d
}
sub minkowskiInv {
my($x) = @_;
return floor($x) + minkowskiInv($x - floor($x)) if $x > 1 || $x < 0;
return $x if $x == 1 || $x == 0 ;
my @contFrac = 0;
my $i = my $curr = 0 ; my $count = 1;
while () {
$x *= 2;
if ($curr == 0) {
if ($x < 1) {
$count++
} else {
$i++;
push @contFrac, 0;
$contFrac[$i-1] = $count;
($count,$curr) = (1,1);
$x--;
}
} else {
if ($x > 1) {
$count++;
$x--;
} else {
$i++;
push @contFrac, 0;
@contFrac[$i-1] = $count;
($count,$curr) = (1,0);
}
}
if ($x == floor($x)) { @contFrac[$i] = $count; last }
last if $i == $MAXITER;
}
my $ret = 1 / $contFrac[$i];
for (my $j = $i - 1; $j >= 0; $j--) { $ret = $contFrac[$j] + 1/$ret }
return 1 / $ret
}
printf "%19.16f%19.16f\n", minkowski(0.5*(1 + sqrt(5))), 5/3;
printf "%19.16f%19.16f\n", minkowskiInv(-5/9), (sqrt(13)-7)/6;
printf "%19.16f%19.16f\n", minkowski(minkowskiInv(0.718281828)), minkowskiInv(minkowski(0.1213141516171819)); | 561Minkowski question-mark function
| 2perl
| thifg |
func F(n: Int) -> Int {
return n == 0? 1: n - M(F(n-1))
}
func M(n: Int) -> Int {
return n == 0? 0: n - F(M(n-1))
}
for i in 0..20 {
print("\(F(i)) ")
}
println()
for i in 0..20 {
print("\(M(i)) ")
}
println() | 542Mutual recursion
| 17swift
| 4i05g |
use strict;
use warnings;
use List::Util 'max';
sub distribution {
my %param = ( function => \&{scalar sub {return 1}}, sample_size => 1e5, @_);
my @values;
do {
my($r1, $r2) = (rand, rand);
push @values, $r1 if &{$param{function}}($r1) > $r2;
} until @values == $param{sample_size};
wantarray ? @values : \@values;
}
sub modifier_notch {
my($x) = @_;
return 2 * ( $x < 1/2 ? ( 1/2 - $x )
: ( $x - 1/2 ) );
}
sub print_histogram {
our %param = (n_bins => 10, width => 80, @_);
my %counts;
$counts{ int($_ * $param{n_bins}) / $param{n_bins} }++ for @{$param{data}};
our $max_value = max values %counts;
print "Bin Counts Histogram\n";
printf "%4.2f%6d:%s\n", $_, $counts{$_}, hist($counts{$_}) for sort keys %counts;
sub hist { scalar ('') x ( $param{width} * $_[0] / $max_value ) }
}
print_histogram( data => \@{ distribution() } );
print "\n\n";
my @samples = distribution( function => \&modifier_notch, sample_size => 50_000);
print_histogram( data => \@samples, n_bins => 20, width => 64); | 563Modified random distribution
| 2perl
| vsy20 |
package main
import (
"fmt"
"strings"
)
const limit = 50000
var (
divs, subs []int
mins [][]string
) | 565Minimal steps down to 1
| 0go
| o4a8q |
import random
from typing import List, Callable, Optional
def modifier(x: float) -> float:
return 2*(.5 - x) if x < 0.5 else 2*(x - .5)
def modified_random_distribution(modifier: Callable[[float], float],
n: int) -> List[float]:
d: List[float] = []
while len(d) < n:
r1 = prob = random.random()
if random.random() < modifier(prob):
d.append(r1)
return d
if __name__ == '__main__':
from collections import Counter
data = modified_random_distribution(modifier, 50_000)
bins = 15
counts = Counter(d
mx = max(counts.values())
print()
last: Optional[float] = None
for b, count in sorted(counts.items()):
delta = 'N/A' if last is None else str(count - last)
print(f
f)
last = count | 563Modified random distribution
| 3python
| u0mvd |
import Data.List
import Data.Ord
import Data.Function (on)
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Integral a => Memo a
nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)
memoize :: Integral a => (a -> b) -> (a -> b)
memoize f = memo (f <$> nats)
data Step = Div Int | Sub Int
deriving Show
run :: Int -> Step -> [(Step, Int)]
run n s = case s of
Sub i | n > i -> [(s, n - i)]
Div d | n `mod` d == 0 -> [(s, n `div` d)]
_ -> []
minSteps :: [Step] -> Int -> (Int, [Step])
minSteps steps = go
where
go = memoize goM
goM 1 = (0, [])
goM n = minimumBy (comparing fst) $ do
(s, k) <- steps >>= run n
let (m, ss) = go k
return (m+1, s:ss) | 565Minimal steps down to 1
| 8haskell
| 2qzll |
import math
MAXITER = 151
def minkowski(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski(x - math.floor(x))
p = int(x)
q = 1
r = p + 1
s = 1
d = 1.0
y = float(p)
while True:
d /= 2
if y + d == y:
break
m = p + r
if m < 0 or p < 0:
break
n = q + s
if n < 0:
break
if x < m / n:
r = m
s = n
else:
y += d
p = m
q = n
return y + d
def minkowski_inv(x):
if x > 1 or x < 0:
return math.floor(x) + minkowski_inv(x - math.floor(x))
if x == 1 or x == 0:
return x
cont_frac = [0]
current = 0
count = 1
i = 0
while True:
x *= 2
if current == 0:
if x < 1:
count += 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 1
x -= 1
else:
if x > 1:
count += 1
x -= 1
else:
cont_frac.append(0)
cont_frac[i] = count
i += 1
count = 1
current = 0
if x == math.floor(x):
cont_frac[i] = count
break
if i == MAXITER:
break
ret = 1.0 / cont_frac[i]
for j in range(i - 1, -1, -1):
ret = cont_frac[j] + 1.0 / ret
return 1.0 / ret
if __name__ == :
print(
.format(
minkowski(0.5 * (1 + math.sqrt(5))),
5.0 / 3.0,
)
)
print(
.format(
minkowski_inv(-5.0 / 9.0),
(math.sqrt(13) - 7) / 6,
)
)
print(
.format(
minkowski(minkowski_inv(0.718281828)),
minkowski_inv(minkowski(0.1213141516171819)),
)
) | 561Minkowski question-mark function
| 3python
| zkntt |
library(NostalgiR)
modifier <- function(x) 2*abs(x - 0.5)
gen <- function()
{
repeat
{
random <- runif(2)
if(random[2] < modifier(random[1])) return(random[1])
}
}
data <- replicate(100000, gen())
NostalgiR::nos.hist(data, breaks = 20, pch = " | 563Modified random distribution
| 13r
| cwz95 |
int main()
{
mpz_t a, b, m, r;
mpz_init_set_str(a,
, 0);
mpz_init_set_str(b,
, 0);
mpz_init(m);
mpz_ui_pow_ui(m, 10, 40);
mpz_init(r);
mpz_powm(r, a, b, m);
gmp_printf(, r);
mpz_clear(a);
mpz_clear(b);
mpz_clear(m);
mpz_clear(r);
return 0;
} | 566Modular exponentiation
| 5c
| 586uk |
package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
} | 562Minimum multiple of m where digital sum equals m
| 0go
| svaqa |
import Data.Bifunctor (first)
import Data.List (elemIndex, intercalate, transpose)
import Data.List.Split (chunksOf)
import Data.Maybe (fromJust)
import Text.Printf (printf)
a131382 :: [Int]
a131382 =
fromJust . (elemIndex <*> productDigitSums)
<$> [1 ..]
productDigitSums :: Int -> [Int]
productDigitSums n = digitSum . (n *) <$> [0 ..]
main :: IO ()
main =
(putStrLn . table " ") $
chunksOf 10 $ show <$> take 40 a131382
digitSum :: Int -> Int
digitSum 0 = 0
digitSum n = uncurry (+) (first digitSum $ quotRem n 10)
table :: String -> [[String]] -> String
table gap rows =
let ws = maximum . fmap length <$> transpose rows
pw = printf . flip intercalate ["%", "s"] . show
in unlines $ intercalate gap . zipWith pw ws <$> rows | 562Minimum multiple of m where digital sum equals m
| 8haskell
| 9ezmo |
(defn powerMod "modular exponentiation" [b e m]
(defn m* [p q] (mod (* p q) m))
(loop [b b, e e, x 1]
(if (zero? e) x
(if (even? e) (recur (m* b b) (/ e 2) x)
(recur (m* b b) (quot e 2) (m* b x)))))) | 566Modular exponentiation
| 6clojure
| jfl7m |
package main
import "fmt" | 564Modular arithmetic
| 0go
| am71f |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MinimalStepsDownToOne {
public static void main(String[] args) {
runTasks(getFunctions1());
runTasks(getFunctions2());
runTasks(getFunctions3());
}
private static void runTasks(List<Function> functions) {
Map<Integer,List<String>> minPath = getInitialMap(functions, 5); | 565Minimal steps down to 1
| 9java
| 6po3z |
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
__int128 res;
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
}
res = b;
while (n > 1) {
res *= b;
n--;
}
return res;
}
__int128 imod(__int128 m, __int128 n) {
__int128 result = m % n;
if (result < 0) {
result += n;
}
return result;
}
bool valid(__int128 n) {
if (n < 0) {
return false;
}
while (n > 0) {
int r = n % 10;
if (r > 1) {
return false;
}
n /= 10;
}
return true;
}
__int128 mpm(const __int128 n) {
__int128 *L;
__int128 m, k, r, j;
if (n == 1) {
return 1;
}
L = calloc(n * n, sizeof(__int128));
L[0] = 1;
L[1] = 1;
m = 0;
while (true) {
m++;
if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
break;
}
L[m * n + 0] = 1;
for (k = 1; k < n; k++) {
L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
}
}
r = ipow(10, m);
k = imod(-r, n);
for (j = m - 1; j >= 1; j--) {
if (L[(j - 1) * n + k] == 0) {
r = r + ipow(10, j);
k = imod(k - ipow(10, j), n);
}
}
if (k == 1) {
r++;
}
return r / n;
}
void print128(__int128 n) {
char buffer[64];
int pos = (sizeof(buffer) / sizeof(char)) - 1;
bool negative = false;
if (n < 0) {
negative = true;
n = -n;
}
buffer[pos] = 0;
while (n > 0) {
int rem = n % 10;
buffer[--pos] = rem + '0';
n /= 10;
}
if (negative) {
buffer[--pos] = '-';
}
printf(&buffer[pos]);
}
void test(__int128 n) {
__int128 mult = mpm(n);
if (mult > 0) {
print128(n);
printf();
print128(mult);
printf();
print128(n * mult);
printf();
} else {
print128(n);
printf();
}
}
int main() {
int i;
for (i = 1; i <= 10; i++) {
test(i);
}
for (i = 95; i <= 105; i++) {
test(i);
}
test(297);
test(576);
test(594);
test(891);
test(909);
test(999);
test(1998);
test(2079);
test(2251);
test(2277);
test(2439);
test(2997);
test(4878);
return 0;
} | 567Minimum positive multiple in base 10 using only 0 and 1
| 5c
| q2jxc |
import Data.Modular
f :: /13 -> /13
f x = x^100 + x + 1
main :: IO ()
main = print (f 10) | 564Modular arithmetic
| 8haskell
| zk8t0 |
public class ModularArithmetic {
private interface Ring<T> {
Ring<T> plus(Ring<T> rhs);
Ring<T> times(Ring<T> rhs);
int value();
Ring<T> one();
default Ring<T> pow(int p) {
if (p < 0) {
throw new IllegalArgumentException("p must be zero or greater");
}
int pp = p;
Ring<T> pwr = this.one();
while (pp-- > 0) {
pwr = pwr.times(this);
}
return pwr;
}
}
private static class ModInt implements Ring<ModInt> {
private int value;
private int modulo;
private ModInt(int value, int modulo) {
this.value = value;
this.modulo = modulo;
}
@Override
public Ring<ModInt> plus(Ring<ModInt> other) {
if (!(other instanceof ModInt)) {
throw new IllegalArgumentException("Cannot add an unknown ring.");
}
ModInt rhs = (ModInt) other;
if (modulo != rhs.modulo) {
throw new IllegalArgumentException("Cannot add rings with different modulus");
}
return new ModInt((value + rhs.value) % modulo, modulo);
}
@Override
public Ring<ModInt> times(Ring<ModInt> other) {
if (!(other instanceof ModInt)) {
throw new IllegalArgumentException("Cannot multiple an unknown ring.");
}
ModInt rhs = (ModInt) other;
if (modulo != rhs.modulo) {
throw new IllegalArgumentException("Cannot multiply rings with different modulus");
}
return new ModInt((value * rhs.value) % modulo, modulo);
}
@Override
public int value() {
return value;
}
@Override
public Ring<ModInt> one() {
return new ModInt(1, modulo);
}
@Override
public String toString() {
return String.format("ModInt(%d,%d)", value, modulo);
}
}
private static <T> Ring<T> f(Ring<T> x) {
return x.pow(100).plus(x).plus(x.one());
}
public static void main(String[] args) {
ModInt x = new ModInt(10, 13);
Ring<ModInt> y = f(x);
System.out.print("x ^ 100 + x + 1 for x = ModInt(10, 13) is ");
System.out.println(y);
System.out.flush();
}
} | 564Modular arithmetic
| 9java
| o4e8d |
use strict;
use warnings;
use ntheory qw( sumdigits );
my @answers = map
{
my $m = 1;
$m++ until sumdigits($m*$_) == $_;
$m;
} 1 .. 70;
print "@answers\n\n" =~ s/.{65}\K /\n/gr; | 562Minimum multiple of m where digital sum equals m
| 2perl
| gi24e |
use strict;
use warnings;
no warnings 'recursion';
use List::Util qw( first );
use Data::Dump 'dd';
for ( [ 2000, [2, 3], [1] ], [ 2000, [2, 3], [2] ] )
{
my ( $n, $div, $sub ) = @$_;
print "\n", '-' x 40, " divisors @$div subtractors @$sub\n";
my ($solve, $max) = minimal( @$_ );
printf "%4d takes%s step(s):%s\n",
$_, $solve->[$_] =~ tr/ // - 1, $solve->[$_] for 1 .. 10;
print "\n";
printf "%d number(s) below%d that take $
$max->[-1] =~ tr/ //, $n, $max->[-1];
($solve, $max) = minimal( 20000, $div, $sub );
printf "%d number(s) below%d that take $
$max->[-1] =~ tr/ //, 20000, $max->[-1];
}
sub minimal
{
my ($top, $div, $sub) = @_;
my @solve = (0, ' ');
my @maximal;
for my $n ( 2 .. $top )
{
my @pick;
for my $d ( @$div )
{
$n % $d and next;
my $ans = "/$d $solve[$n / $d]";
$pick[$ans =~ tr/ //] //= $ans;
}
for my $s ( @$sub )
{
$n > $s or next;
my $ans = "-$s $solve[$n - $s]";
$pick[$ans =~ tr/ //] //= $ans;
}
$solve[$n] = first { defined } @pick;
$maximal[$solve[$n] =~ tr/ // - 1] .= " $n";
}
return \@solve, \@maximal;
} | 565Minimal steps down to 1
| 2perl
| jf27f |
null | 564Modular arithmetic
| 11kotlin
| xlkws |
'''A131382'''
from itertools import count, islice
def a131382():
'''An infinite series of the terms of A131382'''
return (
elemIndex(x)(
productDigitSums(x)
) for x in count(1)
)
def productDigitSums(n):
'''The sum of the decimal digits of n'''
return (digitSum(n * x) for x in count(0))
def main():
'''First 40 terms of A131382'''
print(
table(10)([
str(x) for x in islice(
a131382(),
40
)
])
)
def chunksOf(n):
'''A series of lists of length n, subdividing the
contents of xs. Where the length of xs is not evenly
divisible, the final list will be shorter than n.
'''
def go(xs):
return (
xs[i:n + i] for i in range(0, len(xs), n)
) if 0 < n else None
return go
def digitSum(n):
'''The sum of the digital digits of n.
'''
return sum(int(x) for x in list(str(n)))
def elemIndex(x):
'''Just the first index of x in xs,
or None if no elements match.
'''
def go(xs):
try:
return next(
i for i, v in enumerate(xs) if x == v
)
except StopIteration:
return None
return go
def table(n):
'''A list of strings formatted as
right-justified rows of n columns.
'''
def go(xs):
w = len(xs[-1])
return '\n'.join(
' '.join(row) for row in chunksOf(n)([
s.rjust(w, ' ') for s in xs
])
)
return go
if __name__ == '__main__':
main() | 562Minimum multiple of m where digital sum equals m
| 3python
| rnvgq |
from functools import lru_cache
DIVS = {2, 3}
SUBS = {1}
class Minrec():
def __init__(self, divs=DIVS, subs=SUBS):
self.divs, self.subs = divs, subs
@lru_cache(maxsize=None)
def _minrec(self, n):
if n == 1:
return 0, ['=1']
possibles = {}
for d in self.divs:
if n% d == 0:
possibles[f'/{d}=>{n
for s in self.subs:
if n > s:
possibles[f'-{s}=>{n - s:2}'] = self._minrec(n - s)
thiskind, (count, otherkinds) = min(possibles.items(), key=lambda x: x[1])
ret = 1 + count, [thiskind] + otherkinds
return ret
def __call__(self, n):
ans = self._minrec(n)[1][:-1]
return len(ans), ans
if __name__ == '__main__':
for DIVS, SUBS in [({2, 3}, {1}), ({2, 3}, {2})]:
minrec = Minrec(DIVS, SUBS)
print('\nMINIMUM STEPS TO 1: Recursive algorithm')
print(' Possible divisors: ', DIVS)
print(' Possible decrements:', SUBS)
for n in range(1, 11):
steps, how = minrec(n)
print(f' minrec({n:2}) in {steps:2} by: ', ', '.join(how))
upto = 2000
print(f'\n Those numbers up to {upto} that take the maximum, :')
stepn = sorted((minrec(n)[0], n) for n in range(upto, 0, -1))
mx = stepn[-1][0]
ans = [x[1] for x in stepn if x[0] == mx]
print(' Taking', mx, f'steps is/are the {len(ans)} numbers:',
', '.join(str(n) for n in sorted(ans)))
print() | 565Minimal steps down to 1
| 3python
| htvjw |
function make(value, modulo)
local v = value % modulo
local tbl = {value=v, modulo=modulo}
local mt = {
__add = function(lhs, rhs)
if type(lhs) == "table" then
if type(rhs) == "table" then
if lhs.modulo ~= rhs.modulo then
error("Cannot add rings with different modulus")
end
return make(lhs.value + rhs.value, lhs.modulo)
else
return make(lhs.value + rhs, lhs.modulo)
end
else
error("lhs is not a table in +")
end
end,
__mul = function(lhs, rhs)
if lhs.modulo ~= rhs.modulo then
error("Cannot multiply rings with different modulus")
end
return make(lhs.value * rhs.value, lhs.modulo)
end,
__pow = function(b,p)
if p<0 then
error("p must be zero or greater")
end
local pp = p
local pwr = make(1, b.modulo)
while pp > 0 do
pp = pp - 1
pwr = pwr * b
end
return pwr
end,
__concat = function(lhs, rhs)
if type(lhs) == "table" and type(rhs) == "string" then
return "ModInt("..lhs.value..", "..lhs.modulo..")"..rhs
elseif type(lhs) == "string" and type(rhs) == "table" then
return lhs.."ModInt("..rhs.value..", "..rhs.modulo..")"
else
return "todo"
end
end
}
setmetatable(tbl, mt)
return tbl
end
function func(x)
return x ^ 100 + x + 1
end | 564Modular arithmetic
| 1lua
| q2bx0 |
our $max = 12;
our $width = length($max**2) + 1;
printf "%*s", $width, $_ foreach 'x|', 1..$max;
print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n";
foreach my $i (1..$max) {
printf "%*s", $width, $_
foreach "$i|", map { $_ >= $i and $_*$i } 1..$max;
print "\n";
} | 560Multiplication tables
| 2perl
| q2ex6 |
import Foundation
func digitSum(_ num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n% 10
n /= 10
}
return sum
}
for n in 1...70 {
for m in 1... {
if digitSum(m * n) == n {
print(String(format: "%8d", m), terminator: n% 10 == 0? "\n": " ")
break
}
}
} | 562Minimum multiple of m where digital sum equals m
| 17swift
| 7durq |
func minToOne(divs: [Int], subs: [Int], upTo n: Int) -> ([Int], [[String]]) {
var table = Array(repeating: n + 2, count: n + 1)
var how = Array(repeating: [""], count: n + 2)
table[1] = 0
how[1] = ["="]
for t in 1..<n {
let thisPlus1 = table[t] + 1
for div in divs {
let dt = div * t
if dt <= n && thisPlus1 < table[dt] {
table[dt] = thisPlus1
how[dt] = how[t] + ["/\(div)=> \(t)"]
}
}
for sub in subs {
let st = sub + t
if st <= n && thisPlus1 < table[st] {
table[st] = thisPlus1
how[st] = how[t] + ["-\(sub)=> \(t)"]
}
}
}
return (table, how.map({ $0.reversed().dropLast() }))
}
for (divs, subs) in [([2, 3], [1]), ([2, 3], [2])] {
print("\nMINIMUM STEPS TO 1:")
print(" Possible divisors: \(divs)")
print(" Possible decrements: \(subs)")
let (table, hows) = minToOne(divs: divs, subs: subs, upTo: 10)
for n in 1...10 {
print(" mintab( \(n)) in { \(table[n])} by: ", hows[n].joined(separator: ", "))
}
for upTo in [2_000, 50_000] {
print("\n Those numbers up to \(upTo) that take the maximum, \"minimal steps down to 1\":")
let (table, _) = minToOne(divs: divs, subs: subs, upTo: upTo)
let max = table.dropFirst().max()!
let maxNs = table.enumerated().filter({ $0.element == max })
print(
" Taking", max, "steps are the \(maxNs.count) numbers:",
maxNs.map({ String($0.offset) }).joined(separator: ", ")
)
}
} | 565Minimal steps down to 1
| 17swift
| kzuhx |
Unix build:
make CPPFLAGS=-DNDEBUG LDLIBS=-lcurses mines
dwlmines, by David Lambert; sometime in the twentieth Century. The
program is meant to run in a terminal window compatible with curses
if unix is defined to cpp, or to an ANSI terminal when compiled
without unix macro defined. I suppose I have built this on a
windows 98 computer using gcc running in a cmd window. The original
probably came from a VAX running VMS with a vt100 sort of terminal.
Today I have xterm and gcc available so I will claim only that it
works with this combination.
As this program can automatically play all the trivially counted
safe squares. Action is quick leaving the player with only the
thoughtful action. Whereas 's' steps on the spot with the cursor,
capital 'S' (Stomp) invokes autoplay.
The cursor motion keys are as in the vi editor; hjkl move the cursor.
'd' displays the number of unclaimed bombs and cells.
'f' flags a cell.
The numbers on the field indicate the number of bombs in the
unclaimed neighboring cells. This is more useful than showing the
values you expect. You may find unflagging a cell adjacent to a
number will help you understand this.
There is extra code here. The multidimensional array allocator
allocarray is much better than those of Numerical Recipes in C. If
you subtracted the offset 1 to make the arrays FORTRAN like then
allocarray could substitute for those of NR in C.
void error(int status,const char *message) {
fprintf(stderr, , message);
exit(status);
}
void*dwlcalloc(int n,size_t bytes) {
void*rv = (void*)calloc(n,bytes);
if (NULL == rv)
error(1,);
DEBUG_CODE(fprintf(stderr,,rv);)
return rv;
}
void*allocarray(int rank,size_t*shape,size_t itemSize) {
size_t size,i,j,dataSpace,pointerSpace,pointers,nextLevelIncrement;
char*memory,*pc,*nextpc;
if (rank < 2) {
if (rank < 0)
error(1,);
size = rank < 1 ? 1 : *shape;
return dwlcalloc(size,itemSize);
}
pointerSpace = 0, dataSpace = 1;
for (i = 0; i < rank-1; ++i)
pointerSpace += (dataSpace *= shape[i]);
pointerSpace *= sizeof(char*);
dataSpace *= shape[i]*itemSize;
memory = pc = dwlcalloc(1,pointerSpace+dataSpace);
pointers = 1;
for (i = 0; i < rank-2; ) {
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*sizeof(char*);
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
}
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*itemSize;
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
return memory;
}
if (NULL == print_elt) \
printf(,*(double*)(element)); \
else \
(*print_elt)(element)
void matprint(void*a,int rank,size_t*shape,size_t size,void(*print_elt)()) {
union {
unsigned **ppu;
unsigned *pu;
unsigned u;
} b;
int i;
if (rank <= 0 || NULL == shape)
PRINT(a);
else if (1 < rank) {
for (i = 0; i < shape[0]; ++i)
matprint(((void**)a)[i], rank-1,shape+1,size,print_elt);
putchar('\n');
for (i = 0, b.pu = a; i < shape[0]; ++i, b.u += size) {
PRINT(b.pu);
putchar(' ');
}
}
}
void addch(int c) { putchar(c); }
void addstr(const char*s) { fputs(s,stdout); }
void initscr(void) { printf(,AllocConsole()); }
void cbreak(void) { ; }
void noecho(void) { ; }
void nonl(void) { ; }
int move(int r,int c) { ANSI; return printf(,r+1,c+1); }
int mvaddch(int r,int c,int ch) { move(r,c); addch(ch); }
void refresh(void) { ; }
int attr_on(int a,void*p) { ANSI; return printf(,a); }
int attr_off(int a,void*p) { attr_on(0,NULL); }
void printw(const char*fmt,...) {
va_list args;
va_start(args,fmt);
vprintf(fmt,args);
va_end(args);
}
void clrtoeol(void) {
ANSI;addstr();
}
cell status
UNKN --- contains virgin earth (initial state)
MINE --- has a mine
FLAG --- was flagged
enum {UNKN,MINE,FLAG};
DEBUG_CODE( \
void pchr(void*a) { \
putchar('A'+*(char*a)); \
} \
)
char**bd;
size_t shape[2];
void populate(int x,int y,int pct) {
int i,j,c;
x = BIND(x,4,200), y = BIND(y,4,400);
shape[0] = x+2, shape[1] = y+2; bd = (char**)allocarray(2,shape,sizeof(char));
memset(*bd,1<<UNKN,shape[0]*shape[1]*sizeof(char));
for (i = 0; i < shape[0]; ++i)
bd[i][0] = bd[i][shape[1]-1] = 0;
for (i = 0; i < shape[1]; ++i)
bd[0][i] = bd[shape[0]-1][i] = 0;
{
time_t seed;
printf(,(unsigned)seed);
time(&seed), SRANDOM((unsigned)seed);
}
c = BIND(pct,1,99)*x*y/100;
while(c) {
i = RANDOM(), j = 1+i%y, i = 1+(i>>16)%x;
if (! DETECT(bd[i][j],MINE))
--c, SET_BIT(bd[i][j],MINE);
}
DEBUG_CODE(matprint(bd,2,shape,sizeof(int),pchr);)
RWS = x+1, CLS = y+1;
}
struct {
int i,j;
} neighbor[] = {
{-1,-1}, {-1, 0}, {-1, 1},
{ 0,-1}, { 0, 1},
{ 1,-1}, { 1, 0}, { 1, 1}
};
int cnx(int i,int j,char w) {
int k,c = 0;
for (k = 0; k < DIM(neighbor); ++k)
c += DETECT(NEIGHBOR(i,j,k),w);
return c;
}
int row,col;
int step(void) {
if (DETECT(ME,FLAG)) return 1;
if (DETECT(ME,MINE)) return 0;
CLR_BIT(ME,UNKN);
return 1;
}
int autoplay(void) {
int i,j,k,change,m;
if (!step()) return 0;
do
for (change = 0, i = 1; i < RWS; ++i)
for (j = 1; j < CLS; ++j)
if (!DETECT(bd[i][j],UNKN)) {
m = cnx(i,j,MINE);
if (cnx(i,j,FLAG) == m) {
for (k = 0; k < DIM(neighbor); ++k)
if (DETECT(NEIGHBOR(i,j,k),UNKN)&&!DETECT(NEIGHBOR(i,j,k),FLAG)) {
if (DETECT(NEIGHBOR(i,j,k),MINE)) {
row = i+neighbor[k].i-1, col = j+neighbor[k].j-1;
return 0;
}
change = 1, CLR_BIT(NEIGHBOR(i,j,k),UNKN);
}
} else if (cnx(i,j,UNKN) == m)
for (k = 0; k < DIM(neighbor); ++k)
if (DETECT(NEIGHBOR(i,j,k),UNKN))
change = 1, SET_BIT(NEIGHBOR(i,j,k),FLAG);
}
while (change);
return 1;
}
void takedisplay(void) { initscr(), cbreak(), noecho(), nonl(); }
void help(void) {
move(RWS,1),clrtoeol(), printw();
}
void draw(void) {
int i,j,w;
const char*s1 = ;
move(1,1);
for (i = 1; i < RWS; ++i, addstr())
for (j = 1; j < CLS; ++j, addch(' ')) {
w = bd[i][j];
if (!DETECT(w,UNKN)) {
w = cnx(i,j,MINE)-cnx(i,j,FLAG);
if (w < 0) attr_on(WA_STANDOUT,NULL), w = -w;
addch(s1[w]);
attr_off(WA_STANDOUT,NULL);
}
else if (DETECT(w,FLAG)) addch('F');
else addch('*');
}
move(row+1,2*col+1);
refresh();
}
void show(int win) {
int i,j,w;
const char*s1 = ;
move(1,1);
for (i = 1; i < RWS; ++i, addstr())
for (j = 1; j < CLS; ++j, addch(' ')) {
w = bd[i][j];
if (!DETECT(w,UNKN)) {
w = cnx(i,j,MINE)-cnx(i,j,FLAG);
if (w < 0) attr_on(WA_STANDOUT,NULL), w = -w;
addch(s1[w]);
attr_off(WA_STANDOUT,NULL);
}
else if (DETECT(w,FLAG))
if (DETECT(w,MINE)) addch('F');
else attr_on(WA_STANDOUT,NULL), addch('F'),attr_off(WA_STANDOUT,NULL);
else if (DETECT(w,MINE)) addch('M');
else addch('*');
}
mvaddch(row+1,2*col,'('), mvaddch(row+1,2*(col+1),')');
move(RWS,0);
refresh();
}
const char*s3=, *s4=;
void dbg(int r, int c) {
int i,j,unkns=0,mines=0,flags=0,pct;
char o[6];
static int hint;
for (i = 1; i < RWS; ++i)
for (j = 1; j < CLS; ++j)
unkns += DETECT(bd[i][j],UNKN),
mines += DETECT(bd[i][j],MINE),
flags += DETECT(bd[i][j],FLAG);
move(RWS,1), clrtoeol();
pct = 0.5+100.0*(mines-flags)/MAX(1,unkns-flags);
if (++hint<4)
o[0] = HINTBIT(UNKN), o[1] = HINTBIT(MINE), o[2] = HINTBIT(FLAG),
o[3] = HINTBIT(UNKN), o[4] = NEIGCNT(MINE), o[5] = NEIGCNT(FLAG);
else
memset(o,'?',sizeof(o));
printw(,
o[0],o[1],o[2],o[3],o[4],o[5],mines-flags,unkns-flags,pct);
}
void toggleflag(void) {
if (DETECT(ME,UNKN))
TGL_BIT(ME,FLAG);
}
int sureflag(void) {
toggleflag();
return autoplay();
}
int play(int*win) {
int c = getch(), d = tolower(c);
if ('q' == d) return 0;
else if ('?' == c) help();
else if ('h' == d) col = MODDEC(col,CLS-1);
else if ('l' == d) col = MODINC(col,CLS-1);
else if ('k' == d) row = MODDEC(row,RWS-1);
else if ('j' == d) row = MODINC(row,RWS-1);
else if ('f' == c) toggleflag();
else if ('s' == c) return *win = step();
else if ('S' == c) return *win = autoplay();
else if ('F' == c) return *win = sureflag();
else if ('d' == d) dbg(row+1,col+1);
return 1;
}
int convert(const char*name,const char*s) {
if (strlen(s) == strspn(s,))
return atoi(s);
fprintf(stderr,,name);
fprintf(stderr,,name);
exit(EXIT_SUCCESS);
}
void parse_command_line(int ac,char*av[],int*a,int*b,int*c) {
switch (ac) {
default:
case 4: *c = convert(*av,av[3]);
case 3: *b = convert(*av,av[2]);
case 2: *a = convert(*av,av[1]);
case 1: ;
}
}
int main(int ac,char*av[],char*env[]) {
int win = 1, rows = 20, cols = 30, prct = 25;
parse_command_line(ac,av,&rows,&cols,&prct);
populate(rows,cols,prct);
takedisplay();
while(draw(), play(&win));
show(win);
free(bd);
{
const char*s = ;
execl(s,s,,(const char*)NULL);
}
return 0;
} | 568Minesweeper game
| 5c
| 3bqza |
use Math::ModInt qw(mod);
sub f { my $x = shift; $x**100 + $x + 1 };
print f mod(10, 13); | 564Modular arithmetic
| 2perl
| 2q3lf |
package main
import (
"fmt"
"github.com/shabbyrobe/go-num"
"strings"
"time"
)
func b10(n int64) {
if n == 1 {
fmt.Printf("%4d:%28s %-24d\n", 1, "1", 1)
return
}
n1 := n + 1
pow := make([]int64, n1)
val := make([]int64, n1)
var count, ten, x int64 = 0, 1, 1
for ; x < n1; x++ {
val[x] = ten
for j := int64(0); j < n1; j++ {
if pow[j] != 0 && pow[(j+ten)%n] == 0 && pow[j] != x {
pow[(j+ten)%n] = x
}
}
if pow[ten] == 0 {
pow[ten] = x
}
ten = (10 * ten) % n
if pow[0] != 0 {
break
}
}
x = n
if pow[0] != 0 {
s := ""
for x != 0 {
p := pow[x%n]
if count > p {
s += strings.Repeat("0", int(count-p))
}
count = p - 1
s += "1"
x = (n + x - val[p]) % n
}
if count > 0 {
s += strings.Repeat("0", int(count))
}
mpm := num.MustI128FromString(s)
mul := mpm.Quo64(n)
fmt.Printf("%4d:%28s %-24d\n", n, s, mul)
} else {
fmt.Println("Can't do it!")
}
}
func main() {
start := time.Now()
tests := [][]int64{{1, 10}, {95, 105}, {297}, {576}, {594}, {891}, {909}, {999},
{1998}, {2079}, {2251}, {2277}, {2439}, {2997}, {4878}}
fmt.Println(" n B10 multiplier")
fmt.Println("----------------------------------------------")
for _, test := range tests {
from := test[0]
to := from
if len(test) == 2 {
to = test[1]
}
for n := from; n <= to; n++ {
b10(n)
}
}
fmt.Printf("\nTook%s\n", time.Since(start))
} | 567Minimum positive multiple in base 10 using only 0 and 1
| 0go
| 2qfl7 |
typedef uint8_t card_t;
unsigned int rand_n(unsigned int n) {
unsigned int out, mask = 1;
while (mask < n) mask = mask<<1 | 1;
do {
out = rand() & mask;
} while (out >= n);
return out;
}
card_t rand_card() {
return rand_n(52);
}
void print_card(card_t card) {
static char *suits = ;
static char *cards[] = {,,,,,,,,,,,,};
printf(, cards[card>>2], suits[card&3]);
}
void shuffle(card_t *pack) {
int card;
card_t temp, randpos;
for (card=0; card<52; card++) {
randpos = rand_card();
temp = pack[card];
pack[card] = pack[randpos];
pack[randpos] = temp;
}
}
int trick() {
card_t pack[52];
card_t blacks[52/4], reds[52/4];
card_t top, x, card;
int blackn=0, redn=0, blacksw=0, redsw=0, result;
for (card=0; card<52; card++) pack[card] = card;
shuffle(pack);
printf();
for (card=0; card<52; card += 2) {
top = pack[card];
if (top & 1) {
blacks[blackn++] = pack[card+1];
} else {
reds[redn++] = pack[card+1];
}
print_card(top);
}
printf();
x = rand_n(min(blackn, redn));
for (card=0; card<x; card++) {
blacksw = rand_n(blackn);
redsw = rand_n(redn);
top = blacks[blacksw];
blacks[blacksw] = reds[redsw];
reds[redsw] = top;
}
result = 0;
for (card=0; card<blackn; card++)
result += (blacks[card] & 1) == 1;
for (card=0; card<redn; card++)
result -= (reds[card] & 1) == 0;
result = !result;
printf(
,
result? : );
return result;
}
int main() {
unsigned int seed, i, successes = 0;
FILE *r;
if ((r = fopen(, )) == NULL) {
fprintf(stderr, );
return 255;
}
if (fread(&seed, sizeof(unsigned int), 1, r) != 1) {
fprintf(stderr, );
return 255;
}
fclose(r);
srand(seed);
for (i=1; i<=SIM_N; i++) {
printf(, i);
successes += trick();
printf();
}
printf(,
successes, SIM_N);
return 0;
} | 569Mind boggling card trick
| 5c
| rn6g7 |
import Data.Bifunctor (bimap)
import Data.List (find)
import Data.Maybe (isJust)
b10 :: Integral a => a -> Integer
b10 n = read (digitMatch rems sums) :: Integer
where
(_, rems, _, Just (_, sums)) =
until
(\(_, _, _, mb) -> isJust mb)
( \(e, rems, ms, _) ->
let m = rem (10 ^ e) n
newSums =
(m, [m]):
fmap (bimap (m +) (m:)) ms
in ( succ e,
m: rems,
ms <> newSums,
find
( (0 ==) . flip rem n . fst
)
newSums
)
)
(0, [], [], Nothing)
digitMatch :: Eq a => [a] -> [a] -> String
digitMatch [] _ = []
digitMatch xs [] = '0' <$ xs
digitMatch (x: xs) yys@(y: ys)
| x /= y = '0': digitMatch xs yys
| otherwise = '1': digitMatch xs ys
main :: IO ()
main =
mapM_
( putStrLn
. ( \x ->
let b = b10 x
in justifyRight 5 ' ' (show x)
<> " * "
<> justifyLeft 25 ' ' (show $ div b x)
<> " -> "
<> show b
)
)
( [1 .. 10]
<> [95 .. 105]
<> [297, 576, 594, 891, 909, 999]
)
justifyLeft, justifyRight :: Int -> a -> [a] -> [a]
justifyLeft n c s = take n (s <> replicate n c)
justifyRight n c = (drop . length) <*> (replicate n c <>) | 567Minimum positive multiple in base 10 using only 0 and 1
| 8haskell
| am41g |
package main
import (
"fmt"
"math/big"
)
func main() {
a, _ := new(big.Int).SetString(
"2988348162058574136915891421498819466320163312926952423791023078876139", 10)
b, _ := new(big.Int).SetString(
"2351399303373464486466122544523690094744975233415544072992656881240319", 10)
m := big.NewInt(10)
r := big.NewInt(40)
m.Exp(m, r, nil)
r.Exp(a, b, m)
fmt.Println(r)
} | 566Modular exponentiation
| 0go
| 85p0g |
sem_t sem;
int count = 3;
void acquire()
{
sem_wait(&sem);
count--;
}
void release()
{
count++;
sem_post(&sem);
}
void* work(void * id)
{
int i = 10;
while (i--) {
acquire();
printf(, *(int*)id, getcount());
usleep(rand() % 4000000);
release();
usleep(0);
}
return 0;
}
int main()
{
pthread_t th[4];
int i, ids[] = {1, 2, 3, 4};
sem_init(&sem, 0, count);
for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
for (i = 4; i--;) pthread_join(th[i], 0);
printf();
return sem_destroy(&sem);
} | 570Metered concurrency
| 5c
| 85j04 |
bool Contains(int lst[], int item, int size) {
for (int i = size - 1; i >= 0; i--)
if (item == lst[i]) return true;
return false;
}
int * MianChowla()
{
static int mc[n]; mc[0] = 1;
int sums[nn]; sums[0] = 2;
int sum, le, ss = 1;
for (int i = 1; i < n; i++) {
le = ss;
for (int j = mc[i - 1] + 1; ; j++) {
mc[i] = j;
for (int k = 0; k <= i; k++) {
sum = mc[k] + j;
if (Contains(sums, sum, ss)) {
ss = le; goto nxtJ;
}
sums[ss++] = sum;
}
break;
nxtJ:;
}
}
return mc;
}
int main() {
clock_t st = clock(); int * mc; mc = MianChowla();
double et = ((double)(clock() - st)) / CLOCKS_PER_SEC;
printf();
for (int i = 0; i < 30; i++) printf(, mc[i]);
printf();
for (int i = 90; i < 100; i++) printf(, mc[i]);
printf(, et);
} | 571Mian-Chowla sequence
| 5c
| svgq5 |
println 2988348162058574136915891421498819466320163312926952423791023078876139.modPow(
2351399303373464486466122544523690094744975233415544072992656881240319,
10000000000000000000000000000000000000000) | 566Modular exponentiation
| 7groovy
| wc7el |
modPow :: Integer -> Integer -> Integer -> Integer -> Integer
modPow b e 1 r = 0
modPow b 0 m r = r
modPow b e m r
| e `mod` 2 == 1 = modPow b' e' m (r * b `mod` m)
| otherwise = modPow b' e' m r
where
b' = b * b `mod` m
e' = e `div` 2
main = do
print (modPow 2988348162058574136915891421498819466320163312926952423791023078876139
2351399303373464486466122544523690094744975233415544072992656881240319
(10 ^ 40)
1) | 566Modular exponentiation
| 8haskell
| lxfch |
import operator
import functools
@functools.total_ordering
class Mod:
__slots__ = ['val','mod']
def __init__(self, val, mod):
if not isinstance(val, int):
raise ValueError('Value must be integer')
if not isinstance(mod, int) or mod<=0:
raise ValueError('Modulo must be positive integer')
self.val = val% mod
self.mod = mod
def __repr__(self):
return 'Mod({}, {})'.format(self.val, self.mod)
def __int__(self):
return self.val
def __eq__(self, other):
if isinstance(other, Mod):
if self.mod == other.mod:
return self.val==other.val
else:
return NotImplemented
elif isinstance(other, int):
return self.val == other
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, Mod):
if self.mod == other.mod:
return self.val<other.val
else:
return NotImplemented
elif isinstance(other, int):
return self.val < other
else:
return NotImplemented
def _check_operand(self, other):
if not isinstance(other, (int, Mod)):
raise TypeError('Only integer and Mod operands are supported')
if isinstance(other, Mod) and self.mod != other.mod:
raise ValueError('Inconsistent modulus: {} vs. {}'.format(self.mod, other.mod))
def __pow__(self, other):
self._check_operand(other)
return Mod(pow(self.val, int(other), self.mod), self.mod)
def __neg__(self):
return Mod(self.mod - self.val, self.mod)
def __pos__(self):
return self
def __abs__(self):
return self
def _make_op(opname):
op_fun = getattr(operator, opname)
def op(self, other):
self._check_operand(other)
return Mod(op_fun(self.val, int(other))% self.mod, self.mod)
return op
def _make_reflected_op(opname):
op_fun = getattr(operator, opname)
def op(self, other):
self._check_operand(other)
return Mod(op_fun(int(other), self.val)% self.mod, self.mod)
return op
for opname, reflected_opname in [('__add__', '__radd__'), ('__sub__', '__rsub__'), ('__mul__', '__rmul__')]:
setattr(Mod, opname, _make_op(opname))
setattr(Mod, reflected_opname, _make_reflected_op(opname))
def f(x):
return x**100+x+1
print(f(Mod(10,13))) | 564Modular arithmetic
| 3python
| vs629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.