code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
use Math::Cartesian::Product;
sub playfair {
our($key,$from) = @_;
$from //= 'J';
our $to = $from eq 'J' ? 'I' : '';
my(%ENC,%DEC,%seen,@m);
sub canon {
my($str) = @_;
$str =~ s/[^[:alpha:]]//g;
$str =~ s/$from/$to/gi;
uc $str;
}
my @uniq = grep { ! $seen{$_}++ } split '', canon($key . join '', 'A'..'Z');
while (@uniq) { push @m, [splice @uniq, 0, 5] }
for my $r (@m) {
for my $x (cartesian {@_} [0..4], [0..4]) {
my($i,$j) = @$x;
next if $i == $j;
$ENC{ @$r[$i] . @$r[$j] } = @$r[($i+1)%5] . @$r[($j+1)%5];
}
}
for my $c (0..4) {
my @c = map { @$_[$c] } @m;
for my $x (cartesian {@_} [0..4], [0..4]) {
my($i,$j) = @$x;
next if $i == $j;
$ENC{ $c[$i] . $c[$j] } = $c[($i+1)%5] . $c[($j+1)%5];
}
}
for my $x (cartesian {@_} [0..4], [0..4], [0..4], [0..4]) {
my($i1,$j1,$i2,$j2) = @$x;
next if $i1 == $i2 or $j1 == $j2;
$ENC{ $m[$i1][$j1] . $m[$i2][$j2] } = $m[$i1][$j2] . $m[$i2][$j1];
}
while (my ($k, $v) = each %ENC) { $DEC{$v} = $k }
return
sub { my($red) = @_;
my $str = canon($red);
my @list;
while ($str =~ /(.)(?(?=\1)|(.?))/g) {
push @list, substr($str,$-[0], $-[2] ? 2 : 1);
}
join ' ', map { length($_)==1 ? $ENC{$_.'X'} : $ENC{$_} } @list;
},
sub { my($black) = @_;
join ' ', map { $DEC{$_} } canon($black) =~ /../g;
}
}
my($encode,$decode) = playfair('Playfair example');
my $orig = "Hide the gold in...the TREESTUMP!!!";
my $black = &$encode($orig);
my $red = &$decode($black);
print " orig:\t$orig\n";
print "black:\t$black\n";
print " red:\t$red\n"; | 431Playfair cipher
| 2perl
| 4ff5d |
from PIL import Image
from PIL import ImageColor
from PIL import ImageDraw
x_size = 1650
y_size = 1000
im = Image.new('RGB',(x_size, y_size))
draw = ImageDraw.Draw(im)
White = (255,255,255)
y_delimiter_list = []
for y_delimiter in range(1,y_size,y_size/4):
y_delimiter_list.append(y_delimiter)
for x in range(1,x_size,2):
for y in range(1,y_delimiter_list[1],1):
draw.point((x,y),White)
for x in range(1,x_size-1,4):
for y in range(y_delimiter_list[1],y_delimiter_list[2],1):
draw.point((x,y),White)
draw.point((x+1,y),White)
for x in range(1,x_size-2,6):
for y in range(y_delimiter_list[2],y_delimiter_list[3],1):
draw.point((x,y),White)
draw.point((x+1,y),White)
draw.point((x+2,y),White)
for x in range(1,x_size-3,8):
for y in range(y_delimiter_list[3],y_size,1):
draw.point((x,y),White)
draw.point((x+1,y),White)
draw.point((x+2,y),White)
draw.point((x+3,y),White)
print
im.save('PictureResult.jpg') | 429Pinstripe/Display
| 3python
| q4rxi |
package pig
import (
"fmt"
"math/rand"
"time"
)
type (
PlayerID int
MessageID int
StrategyID int
PigGameData struct {
player PlayerID
turnCount int
turnRollCount int
turnScore int
lastRoll int
scores [2]int
verbose bool
}
)
const ( | 432Pig the dice game/Player
| 0go
| 6we3p |
- player1 always rolls until he gets 20 or more
- player2 always rolls four times
- player3 rolls three times until she gets more than 60 points, then she rolls until she gets 20 or more
- player4 rolls 3/4 of the time, 1/4 he holds, but if he gets a score more than 75 he goes for the win | 432Pig the dice game/Player
| 8haskell
| j637g |
from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i: i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if to is None:
to = 'I' if from_ == 'J' else ''
def canonicalize(s):
return filter(str.isupper, s.upper()).replace(from_, to)
m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)
enc = {}
for row in m:
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[row[i] + row[j]] = row[(i + 1)% 5] + row[(j + 1)% 5]
for c in zip(*m):
for i, j in product(xrange(5), repeat=2):
if i != j:
enc[c[i] + c[j]] = c[(i + 1)% 5] + c[(j + 1)% 5]
for i1, j1, i2, j2 in product(xrange(5), repeat=4):
if i1 != i2 and j1 != j2:
enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]
dec = dict((v, k) for k, v in enc.iteritems())
def sub_enc(txt):
lst = findall(r, canonicalize(txt))
return .join(enc[a + (b if b else 'X')] for a, b in lst)
def sub_dec(encoded):
return .join(dec[p] for p in partition(canonicalize(encoded), 2))
return sub_enc, sub_dec
(encode, decode) = playfair()
orig =
print , orig
enc = encode(orig)
print , enc
print , decode(enc) | 431Playfair cipher
| 3python
| gtt4h |
import java.awt._
import javax.swing._
object PinstripeDisplay extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Pinstripe") {
class Pinstripe_Display extends JPanel {
override def paintComponent(g: Graphics): Unit = {
val bands = 4
super.paintComponent(g)
for (b <- 1 to bands) {
var colIndex = 0
for (x <- 0 until getWidth by b) {
g.setColor(if (colIndex % 2 == 0) Color.white
else Color.black)
g.fillRect(x, (b - 1) * (getHeight / bands), x + b, b * (getHeight / bands))
colIndex += 1
}
}
}
setPreferredSize(new Dimension(900, 600))
}
add(new Pinstripe_Display, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setVisible(true)
})
} | 429Pinstripe/Display
| 16scala
| nkpic |
attr_reader :buffer, :palette, :r, :g, :b, :rd, :gd, :bd, :dim
def settings
size(600, 600)
end
def setup
sketch_title 'Plasma Effect'
frame_rate 25
@r = 42
@g = 84
@b = 126
@rd = true
@gd = true
@bd = true
@dim = width * height
@buffer = Array.new(dim)
grid(width, height) do |x, y|
buffer[x + y * width] = (
(
(128 + (128 * sin(x / 32.0))) +
(128 + (128 * cos(y / 32.0))) +
(128 + (128 * sin(Math.hypot(x, y) / 32.0)))
) / 4
).to_i
end
load_pixels
end
def draw
if rd
@r -= 1
@rd = false if r.negative?
else
@r += 1
@rd = true if r > 128
end
if gd
@g -= 1
@gd = false if g.negative?
else
@g += 1
@gd = true if g > 128
end
if bd
@b -= 1
@bd = false if b.negative?
else
@b += 1
@bd = true if b > 128
end
@palette = (0..127).map do |col|
s1 = sin(col * Math::PI / 25)
s2 = sin(col * Math::PI / 50 + Math::PI / 4)
color(r + s1 * 128, g + s2 * 128, b + s1 * 128)
end
dim.times do |idx|
pixels[idx] = palette[(buffer[idx] + frame_count) & 127]
end
update_pixels
end | 430Plasma effect
| 14ruby
| c089k |
import java.util.Scanner;
public class Pigdice {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int players = 0; | 432Pig the dice game/Player
| 9java
| univv |
extern crate image;
use image::ColorType;
use std::path::Path; | 430Plasma effect
| 15rust
| l8occ |
import java.awt._
import java.awt.event.ActionEvent
import java.awt.image.BufferedImage
import javax.swing._
import scala.math.{sin, sqrt}
object PlasmaEffect extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Plasma Effect") {
class PlasmaEffect extends JPanel {
private val (w, h) = (640, 640)
private var hueShift = 0.0f
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawPlasma(g: Graphics2D) = {
val img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB)
for (y <- 0 until h;
x <- 0 until w) {
def design =
(sin(x / 16f) + sin(y / 8f) + sin((x + y) / 16f) + sin(sqrt(x * x + y * y) / 8f) + 4).toFloat / 8
img.setRGB(x, y, Color.HSBtoRGB(hueShift + design % 1, 1, 1))
}
g.drawImage(img, 0, 0, null)
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawPlasma(g)
} | 430Plasma effect
| 16scala
| undv8 |
def prime(a)
if a == 2
true
elsif a <= 1 || a % 2 == 0
false
else
divisors = (3..Math.sqrt(a)).step(2)
divisors.none? { |d| a % d == 0 }
end
end
p (1..50).select{|i| prime(i)} | 425Primality by trial division
| 14ruby
| 1lgpw |
--Clean up previous run
IF EXISTS (SELECT *
FROM SYS.TYPES
WHERE NAME = 'FairPlayTable')
DROP TYPE FAIRPLAYTABLE
--Set Types
CREATE TYPE FAIRPLAYTABLE AS TABLE (LETTER VARCHAR(1), COLID INT, ROWID INT)
GO
--Configuration Variables
DECLARE @KEYWORD VARCHAR(25) = 'CHARLES' --Keyword for encryption
DECLARE @INPUT VARCHAR(MAX) = 'Testing Seeconqz' --Word to be encrypted
DECLARE @Q INT = 0 -- Q removed?
DECLARE @ENCRYPT INT = 1 --Encrypt?
--Setup Variables
DECLARE @WORDS TABLE
(
WORD_PRE VARCHAR(2),
WORD_POST VARCHAR(2)
)
DECLARE @T_TABLE FAIRPLAYTABLE
DECLARE @NEXTLETTER CHAR(1)
DECLARE @WORD VARCHAR(2),
@COL1 INT,
@COL2 INT,
@ROW1 INT,
@ROW2 INT,
@TMP INT
DECLARE @SQL NVARCHAR(MAX) = '',
@COUNTER INT = 1,
@I INT = 1
DECLARE @COUNTER_2 INT = 1
SET @INPUT = REPLACE(@INPUT, ' ', '')
SET @KEYWORD = UPPER(@KEYWORD)
DECLARE @USEDLETTERS VARCHAR(MAX) = ''
DECLARE @TESTWORDS VARCHAR(2),
@A INT = 0
WHILE @COUNTER_2 <= 5
BEGIN
WHILE @COUNTER <= 5
BEGIN
IF LEN(@KEYWORD) > 0
BEGIN
SET @NEXTLETTER = LEFT(@KEYWORD, 1)
SET @KEYWORD = RIGHT(@KEYWORD, LEN(@KEYWORD) - 1)
IF CHARINDEX(@NEXTLETTER, @USEDLETTERS) = 0
BEGIN
INSERT INTO @T_TABLE
SELECT @NEXTLETTER,
@COUNTER,
@COUNTER_2
SET @COUNTER = @COUNTER + 1
SET @USEDLETTERS = @USEDLETTERS + @NEXTLETTER
END
END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
IF CHARINDEX(CHAR(64 + @I), @USEDLETTERS) = 0
AND NOT ( CHAR(64 + @I) = 'Q'
AND @Q = 1 )
AND NOT ( @Q = 0
AND CHAR(64 + @I) = 'J' )
BEGIN
SET @NEXTLETTER = CHAR(64 + @I)
SET @USEDLETTERS = @USEDLETTERS + CHAR(64 + @I)
SET @I = @I + 1
BREAK
END
SET @I = @I + 1
END
-- SELECT 1 AS [T]
--BREAK
INSERT INTO @T_TABLE
SELECT @NEXTLETTER,
@COUNTER,
@COUNTER_2
SET @COUNTER = @COUNTER + 1
END
END
SET @COUNTER_2 = @COUNTER_2 + 1
SET @COUNTER = 1
END
--Split word into Digraphs
WHILE @A < 1
BEGIN
SET @TESTWORDS = UPPER(LEFT(@INPUT, 2))
IF LEN(@TESTWORDS) = 1
BEGIN
SET @TESTWORDS = @TESTWORDS + 'X'
SET @A = 1
END
ELSE IF RIGHT(@TESTWORDS, 1) = LEFT(@TESTWORDS, 1)
BEGIN
SET @TESTWORDS = RIGHT(@TESTWORDS, 1) + 'X'
SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 1)
END
ELSE
SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 2)
IF LEN(@INPUT) = 0
SET @A = 1
INSERT @WORDS
SELECT @TESTWORDS,
''
END
--Start Encryption
IF @ENCRYPT = 1
BEGIN
--Loop through Digraphs amd encrypt
DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
SELECT WORD_PRE
FROM @WORDS
FOR UPDATE OF WORD_POST
OPEN WORDS_LOOP
FETCH NEXT FROM WORDS_LOOP INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
--Find letter positions
SET @ROW1 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @ROW2 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
SET @COL1 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @COL2 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
--Move positions according to encryption rules
IF @COL1 = @COL2
BEGIN
SET @ROW1 = @ROW1 + 1
SET @ROW2 = @ROW2 + 1
--select 'row'
END
ELSE IF @ROW1 = @ROW2
BEGIN
SET @COL1 = @COL1 + 1
SET @COL2 = @COL2 + 1
--select 'col'
END
ELSE
BEGIN
SET @TMP = @COL2
SET @COL2 = @COL1
SET @COL1 = @TMP
--select 'reg'
END
IF @ROW1 = 6
SET @ROW1 = 1
IF @ROW2 = 6
SET @ROW2 = 1
IF @COL1 = 6
SET @COL1 = 1
IF @COL2 = 6
SET @COL2 = 1
--Find encrypted letters by positions
UPDATE @WORDS
SET WORD_POST = (SELECT (SELECT LETTER
FROM @T_TABLE
WHERE ROWID = @ROW1
AND COLID = @COL1)
+ (SELECT LETTER
FROM @T_TABLE
WHERE COLID = @COL2
AND ROWID = @ROW2))
WHERE WORD_PRE = @WORD
FETCH NEXT FROM WORDS_LOOP INTO @WORD
END
CLOSE WORDS_LOOP
DEALLOCATE WORDS_LOOP
END
--Start Decryption
ELSE
BEGIN
--Loop through Digraphs amd decrypt
DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR
SELECT WORD_PRE
FROM @WORDS
FOR UPDATE OF WORD_POST
OPEN WORDS_LOOP
FETCH NEXT FROM WORDS_LOOP INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
--Find letter positions
SET @ROW1 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @ROW2 = (SELECT ROWID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
SET @COL1 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = LEFT(@WORD, 1))
SET @COL2 = (SELECT COLID
FROM @T_TABLE
WHERE LETTER = RIGHT(@WORD, 1))
--Move positions according to encryption rules
IF @COL1 = @COL2
BEGIN
SET @ROW1 = @ROW1 - 1
SET @ROW2 = @ROW2 - 1
--select 'row'
END
ELSE IF @ROW1 = @ROW2
BEGIN
SET @COL1 = @COL1 - 1
SET @COL2 = @COL2 - 1
--select 'col'
END
ELSE
BEGIN
SET @TMP = @COL2
SET @COL2 = @COL1
SET @COL1 = @TMP
--select 'reg'
END
IF @ROW1 = 0
SET @ROW1 = 5
IF @ROW2 = 0
SET @ROW2 = 5
IF @COL1 = 0
SET @COL1 = 5
IF @COL2 = 0
SET @COL2 = 5
--Find decrypted letters by positions
UPDATE @WORDS
SET WORD_POST = (SELECT (SELECT LETTER
FROM @T_TABLE
WHERE ROWID = @ROW1
AND COLID = @COL1)
+ (SELECT LETTER
FROM @T_TABLE
WHERE COLID = @COL2
AND ROWID = @ROW2))
WHERE WORD_PRE = @WORD
FETCH NEXT FROM WORDS_LOOP INTO @WORD
END
CLOSE WORDS_LOOP
DEALLOCATE WORDS_LOOP
END
--Output
DECLARE WORDS CURSOR LOCAL FAST_FORWARD FOR
SELECT WORD_POST
FROM @WORDS
OPEN WORDS
FETCH NEXT FROM WORDS INTO @WORD
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = @SQL + @WORD + ' '
FETCH NEXT FROM WORDS INTO @WORD
END
CLOSE WORDS
DEALLOCATE WORDS
SELECT @SQL
--Cleanup
IF EXISTS (SELECT *
FROM SYS.TYPES
WHERE NAME = 'FairPlayTable')
DROP TYPE FAIRPLAYTABLE | 431Playfair cipher
| 19sql
| a221t |
const int PRIMES[] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197,
199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379,
383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571,
577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761,
769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977,
};
bool isPrime(const int n) {
int i;
if (n < 2) {
return false;
}
for (i = 0; i < PRIME_SIZE; i++) {
if (n == PRIMES[i]) {
return true;
}
if (n % PRIMES[i] == 0) {
return false;
}
}
if (n < PRIMES[PRIME_SIZE - 1] * PRIMES[PRIME_SIZE - 1]) {
return true;
}
i = PRIMES[PRIME_SIZE - 1]+2;
while (i * i < n) {
if (n % i == 0) {
return false;
}
i += 2;
}
return true;
}
int p[2][50];
void pierpont() {
int64_t s[8 * N];
int count = 0;
int count1 = 1;
int count2 = 0;
int i2 = 0;
int i3 = 0;
int k = 1;
int64_t n2, n3, t;
int64_t *sp = &s[1];
memset(p[0], 0, N * sizeof(int));
memset(p[1], 0, N * sizeof(int));
p[0][0] = 2;
s[0] = 1;
while (count < N) {
n2 = s[i2] * 2;
n3 = s[i3] * 3;
if (n2 < n3) {
t = n2;
i2++;
} else {
t = n3;
i3++;
}
if (t > s[k - 1]) {
*sp++ = t;
k++;
t++;
if (count1 < N && isPrime(t)) {
p[0][count1] = t;
count1++;
}
t -= 2;
if (count2 < N && isPrime(t)) {
p[1][count2] = t;
count2++;
}
count = min(count1, count2);
}
}
}
int main() {
int i;
pierpont();
printf();
for (i = 0; i < N; i++) {
printf(, p[0][i]);
if ((i - 9) % 10 == 0) {
printf();
}
}
printf();
printf();
for (i = 0; i < N; i++) {
printf(, p[1][i]);
if ((i - 9) % 10 == 0) {
printf();
}
}
printf();
} | 433Pierpont primes
| 5c
| wu2ec |
fn is_prime(n: u64) -> bool {
match n {
0 | 1 => false,
2 => true,
_even if n% 2 == 0 => false,
_ => {
let sqrt_limit = (n as f64).sqrt() as u64;
(3..=sqrt_limit).step_by(2).find(|i| n% i == 0).is_none()
}
}
}
fn main() {
for i in (1..30).filter(|i| is_prime(*i)) {
println!("{} ", i);
}
} | 425Primality by trial division
| 15rust
| a2r14 |
const int NUM_PLAYERS = 2;
const int MAX_POINTS = 100;
int randrange(int min, int max){
return (rand() % (max - min + 1)) + min;
}
void ResetScores(int *scores){
for(int i = 0; i < NUM_PLAYERS; i++){
scores[i] = 0;
}
}
void Play(int *scores){
int scoredPoints = 0;
int diceResult;
int choice;
for(int i = 0; i < NUM_PLAYERS; i++){
while(1){
printf(, i + 1, scores[i], scoredPoints);
scanf(, &choice);
if(choice == 1){
diceResult = randrange(1, 6);
printf(, diceResult);
if(diceResult != 1){
scoredPoints += diceResult;
}
else{
printf();
scoredPoints = 0;
break;
}
}
else if(choice == 2){
scores[i] += scoredPoints;
printf(, scores[i]);
break;
}
}
scoredPoints = 0;
CheckForWin(scores[i], i + 1);
}
}
void CheckForWin(int playerScore, int playerNum){
if(playerScore >= MAX_POINTS){
printf(, playerNum);
exit(EXIT_SUCCESS);
}
}
int main()
{
srand(time(0));
int scores[NUM_PLAYERS];
ResetScores(scores);
while(1){
Play(scores);
}
return 0;
} | 434Pig the dice game
| 5c
| c0x9c |
my $GOAL = 100;
package Player;
sub new {
my ($class,$strategy) = @_;
my $self = {
score => 0,
rolls => 0,
ante => 0,
strategy => $strategy || sub { 0 }
};
return bless($self, $class);
}
sub turn {
my ($P) = @_;
$P->{rolls} = 0;
$P->{ante} = 0;
my $done = 0;
do {
my $v = 1 + int rand 6;
$P->{rolls}++;
if ($v == 1) {
$P->{ante} = 0;
$done = 1;
} else {
$P->{ante} += $v;
}
$done = 1 if $P->{score} + $P->{ante} >= $GOAL or $P->{strategy}();
} until $done;
$P->{score} += $P->{ante};
}
package Main;
$players[0] = Player->new;
$players[1] = Player->new( sub { $players[1]->{rolls} >= 5 } );
@players[2] = Player->new( sub { $players[2]->{ante} > 20 } );
$players[3] = Player->new( sub { rand() < 0.1 } );
$players[4] = Player->new( sub { rand() < ( $GOAL - $players[4]->{score} ) * .6 / $GOAL } );
for (1 .. shift || 100) {
my $player = -1;
do {
$player++;
@players[$player % @players]->turn;
} until $players[$player % @players]->{score} >= $GOAL;
$wins[$player % @players]++;
printf "%5d", $players[$_]->{score} for 0..$
$players[$_]->{score} = 0 for 0..$
}
print ' ----' x @players, "\n";
printf "%5d", $_ for @wins; print "\n"; | 432Pig the dice game/Player
| 2perl
| wuve6 |
'''
See: http:
This program scores, throws the dice, and plays for an N player game of Pig.
'''
from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter
playercount = 2
maxscore = 100
maxgames = 100000
Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')
class Player():
def __init__(self, player_index):
self.player_index = player_index
def __repr__(self):
return '%s(%i)'% (self.__class__.__name__, self.player_index)
def __call__(self, safescore, scores, game):
'Returns boolean True to roll again'
pass
class RandPlay(Player):
def __call__(self, safe, scores, game):
'Returns random boolean choice of whether to roll again'
return bool(random.randint(0, 1))
class RollTo20(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and(sum(scores) < 20))
class Desparat(Player):
def __call__(self, safe, scores, game):
'Roll again if this rounds score < 20 or someone is within 20 of winning'
return (((sum(scores) + safe[self.player_index]) < maxscore)
and( (sum(scores) < 20)
or max(safe) >= (maxscore - 20)))
def game__str__(self):
'Pretty printer for Game class'
return (
% (self.players, self.maxscore,
',\n '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__
def winningorder(players, safescores):
'Return (players in winning order, their scores)'
return tuple(zip(*sorted(zip(players, safescores),
key=lambda x: x[1], reverse=True)))
def playpig(game):
'''
Plays the game of pig returning the players in winning order
and their scores whilst updating argument game with the details of play.
'''
players, maxscore, rounds = game
playercount = len(players)
safescore = [0] * playercount
player = 0
scores=[]
while max(safescore) < maxscore:
startscore = safescore[player]
rolling = players[player](safescore, scores, game)
if rolling:
rolled = randint(1, 6)
scores.append(rolled)
if rolled == 1:
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
scores, player = [], (player + 1)% playercount
else:
safescore[player] += sum(scores)
round = Round(who=players[player],
start=startscore,
scores=scores,
safe=safescore[player])
rounds.append(round)
if safescore[player] >= maxscore:
break
scores, player = [], (player + 1)% playercount
return winningorder(players, safescore)
if __name__ == '__main__':
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=20,
rounds=[])
print('ONE GAME')
print('Winning order:%r; Respective scores:%r\n'% playpig(game))
print(game)
game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
maxscore=maxscore,
rounds=[])
algos = (RollTo20, RandPlay, Desparat)
print('\n\nMULTIPLE STATISTICS using%r\n for%i GAMES'
% (', '.join(p.__name__ for p in algos), maxgames,))
winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
for i in range(playercount)),
rounds=[]))[0])
for i in range(maxgames))
print(' Players(position) winning on left; occurrences on right:\n %s'
% ',\n '.join(str(w) for w in winners.most_common())) | 432Pig the dice game/Player
| 3python
| x5uwr |
(def max 100)
(defn roll-dice []
(let [roll (inc (rand-int 6))]
(println "Rolled:" roll) roll))
(defn switch [player]
(if (= player:player1):player2:player1))
(defn find-winner [game]
(cond
(>= (:player1 game) max):player1
(>= (:player2 game) max):player2
:else nil))
(defn bust []
(println "Busted!") 0)
(defn hold [points]
(println "Sticking with" points) points)
(defn play-round [game player temp-points]
(println (format "%s: (%s,%s). Want to Roll? (y/n) " (name player) (player game) temp-points))
(let [input (clojure.string/upper-case (read-line))]
(if (.equals input "Y")
(let [roll (roll-dice)]
(if (= 1 roll)
(bust)
(play-round game player (+ roll temp-points))))
(hold temp-points))))
(defn play-game [game player]
(let [winner (find-winner game)]
(if (nil? winner)
(let [points (play-round game player 0)]
(recur (assoc game player (+ points (player game))) (switch player)))
(println (name winner) "wins!"))))
(defn -main [& args]
(println "Pig the Dice Game.")
(play-game {:player1 0,:player2 0}:player1)) | 434Pig the dice game
| 6clojure
| 5douz |
void _mr_unrank1(int rank, int n, int *vec) {
int t, q, r;
if (n < 1) return;
q = rank / n;
r = rank % n;
SWAP(vec[r], vec[n-1]);
_mr_unrank1(q, n-1, vec);
}
int _mr_rank1(int n, int *vec, int *inv) {
int s, t;
if (n < 2) return 0;
s = vec[n-1];
SWAP(vec[n-1], vec[inv[n-1]]);
SWAP(inv[s], inv[n-1]);
return s + n * _mr_rank1(n-1, vec, inv);
}
void get_permutation(int rank, int n, int *vec) {
int i;
for (i = 0; i < n; ++i) vec[i] = i;
_mr_unrank1(rank, n, vec);
}
int get_rank(int n, int *vec) {
int i, r, *v, *inv;
v = malloc(n * sizeof(int));
inv = malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
v[i] = vec[i];
inv[vec[i]] = i;
}
r = _mr_rank1(n, v, inv);
free(inv);
free(v);
return r;
}
int main(int argc, char *argv[]) {
int i, r, tv[4];
for (r = 0; r < 24; ++r) {
printf(, r);
get_permutation(r, 4, tv);
for (i = 0; i < 4; ++i) {
if (0 == i) printf();
else printf();
printf(, tv[i]);
}
printf(, get_rank(4, tv));
}
} | 435Permutations/Rank of a permutation
| 5c
| l8xcy |
rand() {
printf $(( $1 * RANDOM / 32767 ))
}
rand_element () {
local -a th=("$@")
unset th[0]
printf $'%s\n' "${th[$(($(rand "${
}
echo "You feel like a $(rand_element pig donkey unicorn eagle) today" | 436Pick random element
| 4bash
| fp7d8 |
def isPrime(n: Int) =
n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) | 425Primality by trial division
| 16scala
| x5hwg |
package main
import (
"fmt"
"math/rand"
) | 435Permutations/Rank of a permutation
| 0go
| x5lwf |
int main(){
char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
int i;
time_t t;
srand((unsigned)time(&t));
for(i=0;i<30;i++){
printf(, array[rand()%10]);
}
return 0;
} | 436Pick random element
| 5c
| zahtx |
def player1(sum,sm)
for i in 1..100
puts
a=gets.chomp().to_i
if (a>1 && a<7)
sum+=a
if sum>=100
puts
break
end
else
goto player2(sum,sm)
end
i+=1
end
end
def player2(sum,sm)
for j in 1..100
puts
b=gets.chomp().to_i
if(b>1 && b<7)
sm+=b
if sm>=100
puts
break
end
else
player1(sum,sm)
end
j+=1
end
end
i=0
j=0
sum=0
sm=0
player1(sum,sm)
return | 432Pig the dice game/Player
| 14ruby
| sg4qw |
fact :: Int -> Int
fact n = product [1 .. n]
rankPerm [] _ = []
rankPerm list n = c: rankPerm (a ++ b) r
where
(q, r) = n `divMod` fact (length list - 1)
(a, c:b) = splitAt q list
permRank [] = 0
permRank (x:xs) = length (filter (< x) xs) * fact (length xs) + permRank xs
main :: IO ()
main = mapM_ f [0 .. 23]
where
f n = print (n, p, permRank p)
where
p = rankPerm [0 .. 3] n | 435Permutations/Rank of a permutation
| 8haskell
| yx166 |
package main
import (
"fmt"
big "github.com/ncw/gmp"
"sort"
)
var (
one = new(big.Int).SetUint64(1)
two = new(big.Int).SetUint64(2)
three = new(big.Int).SetUint64(3)
)
func pierpont(ulim, vlim int, first bool) []*big.Int {
p := new(big.Int)
p2 := new(big.Int).Set(one)
p3 := new(big.Int).Set(one)
var pp []*big.Int
for v := 0; v < vlim; v++ {
for u := 0; u < ulim; u++ {
p.Mul(p2, p3)
if first {
p.Add(p, one)
} else {
p.Sub(p, one)
}
if p.ProbablyPrime(10) {
q := new(big.Int)
q.Set(p)
pp = append(pp, q)
}
p2.Mul(p2, two)
}
p3.Mul(p3, three)
p2.Set(one)
}
sort.Slice(pp, func(i, j int) bool {
return pp[i].Cmp(pp[j]) < 0
})
return pp
}
func main() {
fmt.Println("First 50 Pierpont primes of the first kind:")
pp := pierpont(120, 80, true)
for i := 0; i < 50; i++ {
fmt.Printf("%8d ", pp[i])
if (i-9)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 50 Pierpont primes of the second kind:")
pp2 := pierpont(120, 80, false)
for i := 0; i < 50; i++ {
fmt.Printf("%8d ", pp2[i])
if (i-9)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\n250th Pierpont prime of the first kind:", pp[249])
fmt.Println("\n250th Pierpont prime of the second kind:", pp2[249])
} | 433Pierpont primes
| 0go
| c0q9g |
char* reverse_section(char *s, size_t length)
{
if (length == 0) return s;
size_t i; char temp;
for (i = 0; i < length / 2 + 1; ++i)
temp = s[i], s[i] = s[length - i], s[length - i] = temp;
return s;
}
char* reverse_words_in_order(char *s, char delim)
{
if (!strlen(s)) return s;
size_t i, j;
for (i = 0; i < strlen(s) - 1; ++i) {
for (j = 0; s[i + j] != 0 && s[i + j] != delim; ++j)
;
reverse_section(s + i, j - 1);
s += j;
}
return s;
}
char* reverse_string(char *s)
{
return strlen(s) ? reverse_section(s, strlen(s) - 1) : s;
}
char* reverse_order_of_words(char *s, char delim)
{
reverse_string(s);
reverse_words_in_order(s, delim);
return s;
}
int main(void)
{
char str[] = ;
size_t lenstr = sizeof(str) / sizeof(str[0]);
char scopy[lenstr];
char delim = ' ';
printf(%s\, str);
strncpy(scopy, str, lenstr);
reverse_string(scopy);
printf(%s\, scopy);
strncpy(scopy, str, lenstr);
reverse_words_in_order(scopy, delim);
printf(%s\, scopy);
strncpy(scopy, str, lenstr);
reverse_order_of_words(scopy, delim);
printf(%s\, scopy);
return 0;
} | 437Phrase reversals
| 5c
| 6wk32 |
import java.math.BigInteger;
import java.util.*;
class RankPermutation
{
public static BigInteger getRank(int[] permutation)
{
int n = permutation.length;
BitSet usedDigits = new BitSet();
BigInteger rank = BigInteger.ZERO;
for (int i = 0; i < n; i++)
{
rank = rank.multiply(BigInteger.valueOf(n - i));
int digit = 0;
int v = -1;
while ((v = usedDigits.nextClearBit(v + 1)) < permutation[i])
digit++;
usedDigits.set(v);
rank = rank.add(BigInteger.valueOf(digit));
}
return rank;
}
public static int[] getPermutation(int n, BigInteger rank)
{
int[] digits = new int[n];
for (int digit = 2; digit <= n; digit++)
{
BigInteger divisor = BigInteger.valueOf(digit);
digits[n - digit] = rank.mod(divisor).intValue();
if (digit < n)
rank = rank.divide(divisor);
}
BitSet usedDigits = new BitSet();
int[] permutation = new int[n];
for (int i = 0; i < n; i++)
{
int v = usedDigits.nextClearBit(0);
for (int j = 0; j < digits[i]; j++)
v = usedDigits.nextClearBit(v + 1);
permutation[i] = v;
usedDigits.set(v);
}
return permutation;
}
public static void main(String[] args)
{
for (int i = 0; i < 6; i++)
{
int[] permutation = getPermutation(3, BigInteger.valueOf(i));
System.out.println(String.valueOf(i) + " --> " + Arrays.toString(permutation) + " --> " + getRank(permutation));
}
Random rnd = new Random();
for (int n : new int[] { 12, 144 })
{
BigInteger factorial = BigInteger.ONE;
for (int i = 2; i <= n; i++)
factorial = factorial.multiply(BigInteger.valueOf(i)); | 435Permutations/Rank of a permutation
| 9java
| db7n9 |
import Control.Monad (guard)
import Data.List (intercalate)
import Data.List.Split (chunksOf)
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime)
import Math.NumberTheory.Primes.Testing (isPrime)
import Text.Printf (printf)
data PierPointKind = First | Second
merge :: Ord a => [a] -> [a] -> [a]
merge [] b = b
merge a@(x:xs) b@(y:ys) | x < y = x: merge xs b
| otherwise = y: merge a ys
nSmooth :: Integer -> [Integer]
nSmooth p = 1: foldr u [] factors
where
factors = takeWhile (<=p) primes
primes = map unPrime [nextPrime 1..]
u n s = r
where
r = merge s (map (n*) (1:r))
pierpoints :: PierPointKind -> [Integer]
pierpoints k = do
n <- nSmooth 3
let x = case k of First -> succ n
Second -> pred n
guard (isPrime x) >> [x]
main :: IO ()
main = do
printf "\nFirst 50 Pierpont primes of the first kind:\n"
mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints First)
printf "\nFirst 50 Pierpont primes of the second kind:\n"
mapM_ (\row -> mapM_ (printf "%12s" . commas) row >> printf "\n") (rows $ pierpoints Second)
printf "\n250th Pierpont prime of the first kind:%s\n" (commas $ pierpoints First !! 249)
printf "\n250th Pierpont prime of the second kind:%s\n\n" (commas $ pierpoints Second !! 249)
where
rows = chunksOf 10 . take 50
commas = reverse . intercalate "," . chunksOf 3 . reverse . show | 433Pierpont primes
| 8haskell
| pcmbt |
(rand-nth coll) | 436Pick random element
| 6clojure
| 9sama |
int locale_ok = 0;
wchar_t s_suits[] = L;
const char *s_suits_ascii[] = { , , , };
const char *s_nums[] = { ,
, , , , , , , , , , , , ,
};
typedef struct { int suit, number, _s; } card_t, *card;
typedef struct { int n; card_t cards[52]; } deck_t, *deck;
void show_card(card c)
{
if (locale_ok)
printf(, s_suits[c->suit], s_nums[c->number]);
else
printf(, s_suits_ascii[c->suit], s_nums[c->number]);
}
deck new_deck()
{
int i, j, k;
deck d = malloc(sizeof(deck_t));
d->n = 52;
for (i = k = 0; i < 4; i++)
for (j = 1; j <= 13; j++, k++) {
d->cards[k].suit = i;
d->cards[k].number = j;
}
return d;
}
void show_deck(deck d)
{
int i;
printf(, d->n);
for (i = 0; i < d->n; i++)
show_card(d->cards + i);
printf();
}
int cmp_card(const void *a, const void *b)
{
int x = ((card)a)->_s, y = ((card)b)->_s;
return x < y ? -1 : x > y;
}
card deal_card(deck d)
{
if (!d->n) return 0;
return d->cards + --d->n;
}
void shuffle_deck(deck d)
{
int i;
for (i = 0; i < d->n; i++)
d->cards[i]._s = rand();
qsort(d->cards, d->n, sizeof(card_t), cmp_card);
}
int main()
{
int i, j;
deck d = new_deck();
locale_ok = (0 != setlocale(LC_CTYPE, ));
printf(); show_deck(d);
printf();
shuffle_deck(d);
for (i = 0; i < 3; i++) {
for (j = 0; j < 5; j++)
show_card(deal_card(d));
printf();
}
printf(); show_deck(d);
return 0;
} | 438Playing cards
| 5c
| l8acy |
declare @number int
set @number = 514229 -- number to check
;with cte(number) as
(
select 2
union all
select number+1
from cte
where number+1 < @number
)
select
cast(@number as varchar(100)) +
case
when exists
(
select *
from
(
select number, @number % number modNumber
from cte
) tmp
where tmp.modNumber = 0
)
then ' is composite'
else
' is prime'
end primalityTest
option (maxrecursion 0) | 425Primality by trial division
| 19sql
| 0rps1 |
use strict;
use warnings;
my $svg = <<'EOD';
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" width="1200" height="825">
<rect width="100%" height="100%" fill="
<defs>
<g id="block">
<polygon points="-25,-25,-25,25,25,25" fill="white" />
<polygon points="25,25,25,-25,-25,-25" fill="black" />
<rect x="-20" y="-20" width="40" height="40" fill="
</g>
</defs>
EOD
for my $X (1..15) {
for my $Y (1..10) {
my $r = int(($X + $Y) / 2) % 4 * 90;
my $x = $X * 75;
my $y = $Y * 75;
my $a = $r > 0 ? "rotate($r,$x,$y) " : '';
$svg .= qq{<use xlink:href="
}
}
$svg .= '</svg>';
open my $fh, '>', 'peripheral-drift.svg';
print $fh $svg;
close $fh; | 439Peripheral drift illusion
| 2perl
| b9dk4 |
null | 435Permutations/Rank of a permutation
| 11kotlin
| 0rusf |
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
public class PierpontPrimes {
public static void main(String[] args) {
NumberFormat nf = NumberFormat.getNumberInstance();
display("First 50 Pierpont primes of the first kind:", pierpontPrimes(50, true));
display("First 50 Pierpont primes of the second kind:", pierpontPrimes(50, false));
System.out.printf("250th Pierpont prime of the first kind: %s%n%n", nf.format(pierpontPrimes(250, true).get(249)));
System.out.printf("250th Pierpont prime of the second kind:%s%n%n", nf.format(pierpontPrimes(250, false).get(249)));
}
private static void display(String message, List<BigInteger> primes) {
NumberFormat nf = NumberFormat.getNumberInstance();
System.out.printf("%s%n", message);
for ( int i = 1 ; i <= primes.size() ; i++ ) {
System.out.printf("%10s ", nf.format(primes.get(i-1)));
if ( i % 10 == 0 ) {
System.out.printf("%n");
}
}
System.out.printf("%n");
}
public static List<BigInteger> pierpontPrimes(int n, boolean first) {
List<BigInteger> primes = new ArrayList<BigInteger>();
if ( first ) {
primes.add(BigInteger.valueOf(2));
n -= 1;
}
BigInteger two = BigInteger.valueOf(2);
BigInteger twoTest = two;
BigInteger three = BigInteger.valueOf(3);
BigInteger threeTest = three;
int twoIndex = 0, threeIndex = 0;
List<BigInteger> twoSmooth = new ArrayList<BigInteger>();
BigInteger one = BigInteger.ONE;
BigInteger mOne = BigInteger.valueOf(-1);
int count = 0;
while ( count < n ) {
BigInteger min = twoTest.min(threeTest);
twoSmooth.add(min);
if ( min.compareTo(twoTest) == 0 ) {
twoTest = two.multiply(twoSmooth.get(twoIndex));
twoIndex++;
}
if ( min.compareTo(threeTest) == 0 ) {
threeTest = three.multiply(twoSmooth.get(threeIndex));
threeIndex++;
}
BigInteger test = min.add(first ? one : mOne);
if ( test.isProbablePrime(10) ) {
primes.add(test);
count++;
}
}
return primes;
}
} | 433Pierpont primes
| 9java
| rzfg0 |
(use '[clojure.string:only (join split)])
(def phrase "rosetta code phrase reversal")
(defn str-reverse [s] (apply str (reverse s)))
(str-reverse phrase)
(join " " (map str-reverse (split phrase #" ")))
(apply str (interpose " " (reverse (split phrase #" ")))) | 437Phrase reversals
| 6clojure
| l8ecb |
import Foundation
extension Int {
func isPrime() -> Bool {
switch self {
case let x where x < 2:
return false
case 2:
return true
default:
return
self% 2!= 0 &&
!stride(from: 3, through: Int(sqrt(Double(self))), by: 2).contains {self% $0 == 0}
}
}
} | 425Primality by trial division
| 17swift
| pc4bl |
int data[] = { 85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98 };
int pick(int at, int remain, int accu, int treat)
{
if (!remain) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat) +
( at > remain ? pick(at - 1, remain, accu, treat) : 0 );
}
int main()
{
int treat = 0, i;
int le, gt;
double total = 1;
for (i = 0; i < 9; i++) treat += data[i];
for (i = 19; i > 10; i--) total *= i;
for (i = 9; i > 0; i--) total /= i;
gt = pick(19, 9, 0, treat);
le = total - gt;
printf(,
100 * le / total, le, 100 * gt / total, gt);
return 0;
} | 440Permutation test
| 5c
| fp5d3 |
typedef unsigned uint;
uint is_pern(uint n)
{
uint c = 2693408940u;
while (n) c >>= 1, n &= (n - 1);
return c & 1;
}
int main(void)
{
uint i, c;
for (i = c = 0; c < 25; i++)
if (is_pern(i))
printf(, i), ++c;
putchar('\n');
for (i = 888888877u; i <= 888888888u; i++)
if (is_pern(i))
printf(, i);
putchar('\n');
return 0;
} | 441Pernicious numbers
| 5c
| 0rmst |
import java.math.BigInteger
import kotlin.math.min
val one: BigInteger = BigInteger.ONE
val two: BigInteger = BigInteger.valueOf(2)
val three: BigInteger = BigInteger.valueOf(3)
fun pierpont(n: Int): List<List<BigInteger>> {
val p = List(2) { MutableList(n) { BigInteger.ZERO } }
p[0][0] = two
var count = 0
var count1 = 1
var count2 = 0
val s = mutableListOf<BigInteger>()
s.add(one)
var i2 = 0
var i3 = 0
var k = 1
var n2: BigInteger
var n3: BigInteger
var t: BigInteger
while (count < n) {
n2 = s[i2] * two
n3 = s[i3] * three
if (n2 < n3) {
t = n2
i2++
} else {
t = n3
i3++
}
if (t > s[k - 1]) {
s.add(t)
k++
t += one
if (count1 < n && t.isProbablePrime(10)) {
p[0][count1] = t
count1++
}
t -= two
if (count2 < n && t.isProbablePrime(10)) {
p[1][count2] = t
count2++
}
count = min(count1, count2)
}
}
return p
}
fun main() {
val p = pierpont(2000)
println("First 50 Pierpont primes of the first kind:")
for (i in 0 until 50) {
print("%8d ".format(p[0][i]))
if ((i - 9) % 10 == 0) {
println()
}
}
println("\nFirst 50 Pierpont primes of the second kind:")
for (i in 0 until 50) {
print("%8d ".format(p[1][i]))
if ((i - 9) % 10 == 0) {
println()
}
}
println("\n250th Pierpont prime of the first kind: ${p[0][249]}")
println("\n250th Pierpont prime of the first kind: ${p[1][249]}")
println("\n1000th Pierpont prime of the first kind: ${p[0][999]}")
println("\n1000th Pierpont prime of the first kind: ${p[1][999]}")
println("\n2000th Pierpont prime of the first kind: ${p[0][1999]}")
println("\n2000th Pierpont prime of the first kind: ${p[1][1999]}")
} | 433Pierpont primes
| 11kotlin
| vi821 |
(def suits [:club:diamond:heart:spade])
(def pips [:ace 2 3 4 5 6 7 8 9 10:jack:queen:king])
(defn deck [] (for [s suits p pips] [s p]))
(def shuffle clojure.core/shuffle)
(def deal first)
(defn output [deck]
(doseq [[suit pip] deck]
(println (format "%s of%ss"
(if (keyword? pip) (name pip) pip)
(name suit))))) | 438Playing cards
| 6clojure
| 4fs5o |
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano()) | 434Pig the dice game
| 0go
| wuleg |
use ntheory qw/:all/;
my $n = 3;
print " Iterate Lexicographic rank/unrank of $n objects\n";
for my $k (0 .. factorial($n)-1) {
my @perm = numtoperm($n, $k);
my $rank = permtonum(\@perm);
die unless $rank == $k;
printf "%2d --> [@perm] -->%2d\n", $k, $rank;
}
print "\n";
print " Four 12-object random permutations using ranks\n";
print join(" ", numtoperm(12,urandomm(factorial(12)))), "\n" for 1..4;
print "\n";
print " Four 12-object random permutations using randperm\n";
print join(" ", randperm(12)),"\n" for 1..4;
print "\n";
print " Four 4-object random permutations of 100k objects using randperm\n";
print join(" ", randperm(100000,4)),"\n" for 1..4; | 435Permutations/Rank of a permutation
| 2perl
| 5d8u2 |
local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local f, limit = 5, math.sqrt(n)
for f = 5, limit, 6 do
if n % f == 0 then return false end
if n % (f+2) == 0 then return false end
end
return true
end
local function s3iter()
local s, i2, i3 = {1}, 1, 1
return function()
local n2, n3, val = 2*s[i2], 3*s[i3], s[#s]
s[#s+1] = math.min(n2, n3)
i2, i3 = i2 + (n2<=n3 and 1 or 0), i3 + (n2>=n3 and 1 or 0)
return val
end
end
local function pierpont(n)
local list1, list2, s3next = {}, {}, s3iter()
while #list1 < n or #list2 < n do
local s3 = s3next()
if #list1 < n then
if isprime(s3+1) then list1[#list1+1] = s3+1 end
end
if #list2 < n then
if isprime(s3-1) then list2[#list2+1] = s3-1 end
end
end
return list1, list2
end
local N = 50
local p1, p2 = pierpont(N)
print("First 50 Pierpont primes of the first kind:")
for i, p in ipairs(p1) do
io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end
print()
print("First 50 Pierpont primes of the second kind:")
for i, p in ipairs(p2) do
io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end | 433Pierpont primes
| 1lua
| unovl |
int flag = 1;
void heapPermute(int n, int arr[],int arrLen){
int temp;
int i;
if(n==1){
printf();
for(i=0;i<arrLen;i++)
printf(,arr[i]);
printf(,flag);
flag*=-1;
}
else{
for(i=0;i<n-1;i++){
heapPermute(n-1,arr,arrLen);
if(n%2==0){
temp = arr[i];
arr[i] = arr[n-1];
arr[n-1] = temp;
}
else{
temp = arr[0];
arr[0] = arr[n-1];
arr[n-1] = temp;
}
}
heapPermute(n-1,arr,arrLen);
}
}
int main(int argC,char* argV[0])
{
int *arr, i=0, count = 1;
char* token;
if(argC==1)
printf(,argV[0]);
else{
while(argV[1][i]!=00){
if(argV[1][i++]==',')
count++;
}
arr = (int*)malloc(count*sizeof(int));
i = 0;
token = strtok(argV[1],);
while(token!=NULL){
arr[i++] = atoi(token);
token = strtok(NULL,);
}
heapPermute(i,arr,count);
}
return 0;
} | 442Permutations by swapping
| 5c
| db2nv |
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
got -= 2;
while (s[got] == '0' || s[got] == '9') got--;
printf(, (int)(got - done), s + done);
free(s);
done = got;
accu *= 2;
}
return 0;
} | 443Pi
| 5c
| evdav |
class PigDice {
final static int maxScore = 100;
final static yesses = ["yes", "y", "", "Y", "YES"]
static main(args) {
def playersCount = 2
Scanner sc = new Scanner(System.in)
Map scores = [:]
def current = 0
def player = 0
def gameOver = false
def firstThrow = true
Random rnd = new Random() | 434Pig the dice game
| 7groovy
| b96ky |
import System.Random (randomRIO)
data Score = Score { stack :: Int, score :: Int }
main :: IO ()
main = loop (Score 0 0) (Score 0 0)
loop :: Score -> Score -> IO ()
loop p1 p2 = do
putStrLn $ "\nPlayer 1 ~ " ++ show (score p1)
p1' <- askPlayer p1
if (score p1') >= 100
then putStrLn "P1 won!"
else do
putStrLn $ "\nPlayer 2 ~ " ++ show (score p2)
p2' <- askPlayer p2
if (score p2') >= 100
then putStrLn "P2 won!"
else loop p1' p2'
askPlayer :: Score -> IO Score
askPlayer (Score stack score) = do
putStr "\n(h)old or (r)oll? "
answer <- getChar
roll <- randomRIO (1,6)
case (answer, roll) of
('h', _) -> do
putStrLn $ " => Score = " ++ show (stack + score)
return $ Score 0 (stack + score)
('r', 1) -> do
putStrLn $ " => 1 => Sorry - stack was resetted"
return $ Score 0 score
('r', _) -> do
putStr $ " => " ++ show roll ++ " => current stack = " ++ show (stack + roll)
askPlayer $ Score (stack + roll) score
_ -> do
putStrLn "\nInvalid input - please try again."
askPlayer $ Score stack score | 434Pig the dice game
| 8haskell
| 6w13k |
(defn counting-numbers
([] (counting-numbers 1))
([n] (lazy-seq (cons n (counting-numbers (inc n))))))
(defn divisors [n] (filter #(zero? (mod n %)) (range 1 (inc n))))
(defn prime? [n] (= (divisors n) (list 1 n)))
(defn pernicious? [n]
(prime? (count (filter #(= % \1) (Integer/toString n 2)))))
(println (take 25 (filter pernicious? (counting-numbers))))
(println (filter pernicious? (range 888888877 888888889))) | 441Pernicious numbers
| 6clojure
| dbvnb |
from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return pi
def init_pi1(n, pi):
pi1 = [-1] * n
for i in range(n):
pi1[pi[i]] = i
return pi1
def ranker1(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s + n * ranker1(n1, pi, pi1)
def unranker2(n, r, pi):
while n > 0:
n1 = n-1
s, rmodf = divmod(r, fact(n1))
pi[n1], pi[s] = pi[s], pi[n1]
n = n1
r = rmodf
return pi
def ranker2(n, pi, pi1):
if n == 1:
return 0
n1 = n-1
s = pi[n1]
pi[n1], pi[pi1[n1]] = pi[pi1[n1]], pi[n1]
pi1[s], pi1[n1] = pi1[n1], pi1[s]
return s * fact(n1) + ranker2(n1, pi, pi1)
def get_random_ranks(permsize, samplesize):
perms = fact(permsize)
ranks = set()
while len(ranks) < samplesize:
ranks |= set( randrange(perms)
for r in range(samplesize - len(ranks)) )
return ranks
def test1(comment, unranker, ranker):
n, samplesize, n2 = 3, 4, 12
print(comment)
perms = []
for r in range(fact(n)):
pi = identity_perm(n)
perm = unranker(n, r, pi)
perms.append((r, perm))
for r, pi in perms:
pi1 = init_pi1(n, pi)
print(' From rank%2i to%r back to%2i'% (r, pi, ranker(n, pi[:], pi1)))
print('\n %i random individual samples of%i items:'% (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + ' '.join('%2i'% i for i in unranker(n2, r, pi)))
print('')
def test2(comment, unranker):
samplesize, n2 = 4, 144
print(comment)
print(' %i random individual samples of%i items:'% (samplesize, n2))
for r in get_random_ranks(n2, samplesize):
pi = identity_perm(n2)
print(' ' + '\n '.join(wrap(repr(unranker(n2, r, pi)))))
print('')
if __name__ == '__main__':
test1('First ordering:', unranker1, ranker1)
test1('Second ordering:', unranker2, ranker2)
test2('First ordering, large number of perms:', unranker1) | 435Permutations/Rank of a permutation
| 3python
| 4fo5k |
typedef unsigned long long LONG;
LONG deranged(int depth, int len, int *d, int show)
{
int i;
char tmp;
LONG count = 0;
if (depth == len) {
if (show) {
for (i = 0; i < len; i++) putchar(d[i] + 'a');
putchar('\n');
}
return 1;
}
for (i = len - 1; i >= depth; i--) {
if (i == d[depth]) continue;
tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
count += deranged(depth + 1, len, d, show);
tmp = d[i]; d[i] = d[depth]; d[depth] = tmp;
}
return count;
}
LONG gen_n(int n, int show)
{
LONG i;
int a[1024];
for (i = 0; i < n; i++) a[i] = i;
return deranged(0, n, a, show);
}
LONG sub_fact(int n)
{
return n < 2 ? 1 - n : (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1);
}
int main()
{
int i;
printf();
gen_n(4, 1);
printf();
for (i = 0; i < 10; i++)
printf(, i, gen_n(i, 0), sub_fact(i));
printf();
for (i = 10; i <= 20; i++)
printf(, i, sub_fact(i));
return 0;
} | 444Permutations/Derangements
| 5c
| x5fwu |
(defn permutation-swaps
"List of swap indexes to generate all permutations of n elements"
[n]
(if (= n 2) `((0 1))
(let [old-swaps (permutation-swaps (dec n))
swaps-> (partition 2 1 (range n))
swaps<- (reverse swaps->)]
(mapcat (fn [old-swap side]
(case side
:first swaps<-
:right (conj swaps<- old-swap)
:left (conj swaps-> (map inc old-swap))))
(conj old-swaps nil)
(cons:first (cycle '(:left:right)))))))
(defn swap [v [i j]]
(-> v
(assoc i (nth v j))
(assoc j (nth v i))))
(defn permutations [n]
(let [permutations (reduce
(fn [all-perms new-swap]
(conj all-perms (swap (last all-perms)
new-swap)))
(vector (vec (range n)))
(permutation-swaps n))
output (map vector
permutations
(cycle '(1 -1)))]
output))
(doseq [n [2 3 4]]
(dorun (map println (permutations n)))) | 442Permutations by swapping
| 6clojure
| 6wg3q |
int p[512];
double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); }
double lerp(double t, double a, double b) { return a + t * (b - a); }
double grad(int hash, double x, double y, double z) {
int h = hash & 15;
double u = h<8 ? x : y,
v = h<4 ? y : h==12||h==14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
double noise(double x, double y, double z) {
int X = (int)floor(x) & 255,
Y = (int)floor(y) & 255,
Z = (int)floor(z) & 255;
x -= floor(x);
y -= floor(y);
z -= floor(z);
double u = fade(x),
v = fade(y),
w = fade(z);
int A = p[X ]+Y, AA = p[A]+Z, AB = p[A+1]+Z,
B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA ], x , y , z ),
grad(p[BA ], x-1, y , z )),
lerp(u, grad(p[AB ], x , y-1, z ),
grad(p[BB ], x-1, y-1, z ))),
lerp(v, lerp(u, grad(p[AA+1], x , y , z-1 ),
grad(p[BA+1], x-1, y , z-1 )),
lerp(u, grad(p[AB+1], x , y-1, z-1 ),
grad(p[BB+1], x-1, y-1, z-1 ))));
}
void loadPermutation(char* fileName){
FILE* fp = fopen(fileName,);
int permutation[256],i;
for(i=0;i<256;i++)
fscanf(fp,,&permutation[i]);
fclose(fp);
for (int i=0; i < 256 ; i++) p[256+i] = p[i] = permutation[i];
}
int main(int argC,char* argV[])
{
if(argC!=5)
printf();
else{
loadPermutation(argV[1]);
printf(,argV[2],argV[3],argV[4],noise(strtod(argV[2],NULL),strtod(argV[3],NULL),strtod(argV[4],NULL)));
}
return 0;
} | 445Perlin noise
| 5c
| yx56f |
package main
import (
"fmt"
"log"
)
var limits = [][2]int{
{3, 10}, {11, 18}, {19, 36}, {37, 54}, {55, 86}, {87, 118},
}
func periodicTable(n int) (int, int) {
if n < 1 || n > 118 {
log.Fatal("Atomic number is out of range.")
}
if n == 1 {
return 1, 1
}
if n == 2 {
return 1, 18
}
if n >= 57 && n <= 71 {
return 8, n - 53
}
if n >= 89 && n <= 103 {
return 9, n - 85
}
var row, start, end int
for i := 0; i < len(limits); i++ {
limit := limits[i]
if n >= limit[0] && n <= limit[1] {
row, start, end = i+2, limit[0], limit[1]
break
}
}
if n < start+2 || row == 4 || row == 5 {
return row, n - start + 1
}
return row, n - end + 18
}
func main() {
for _, n := range []int{1, 2, 29, 42, 57, 58, 59, 71, 72, 89, 90, 103, 113} {
row, col := periodicTable(n)
fmt.Printf("Atomic number%3d ->%d,%-2d\n", n, row, col)
}
} | 446Periodic table
| 0go
| sgfqa |
(ns pidigits
(:gen-class))
(def calc-pi
(let [div (fn [x y] (long (Math/floor (/ x y))))
update-after-yield (fn [[q r t k n l]]
(let [nr (* 10 (- r (* n t)))
nn (- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
nq (* 10 q)]
[nq nr t k nn l]))
update-else (fn [[q r t k n l]]
(let [nr (* (+ (* 2 q) r) l)
nn (div (+ (* q 7 k) 2 (* r l)) (* t l))
nq (* k q)
nt (* l t)
nl (+ 2 l)
nk (+ 1 k)]
[nq nr nt nk nn nl]))
pi-from (fn pi-from [[q r t k n l]]
(if (< (- (+ (* 4 q) r) t) (* n t))
(lazy-seq (cons n (pi-from (update-after-yield [q r t k n l]))))
(recur (update-else [q r t k n l]))))]
(pi-from [1N 0N 1N 1N 3N 3N])))
(doseq [[i q] (map-indexed vector calc-pi)]
(when (= (mod i 40) 0)
(println))
(print q)) | 443Pi
| 6clojure
| 0r6sj |
use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<is_prime>;
sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$
sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++; } }
sub iter2 { my $m = shift; my $e = 1; return sub { $m * ($e *= 2) } }
sub pierpont {
my($max ) = shift || die 'Must specify count of primes to generate.';
my($kind) = @_ ? shift : 1;
die "Unknown type: $kind. Must be one of 1 (default) or 2" unless $kind == 1 || $kind == 2;
$kind = -1 if $kind == 2;
my $po3 = 3;
my $add_one = 3;
my @iterators;
push @iterators, iter1(2);
push @iterators, iter1(3); $iterators[1]->();
my @head = ($iterators[0]->(), $iterators[1]->());
my @pierpont;
do {
my $key = min_index(@head);
my $min = $head[$key];
push @pierpont, $min + $kind if is_prime($min + $kind);
$head[$key] = $iterators[$key]->();
if ($min >= $add_one) {
push @iterators, iter2($po3);
$add_one = $head[$
$po3 *= 3;
}
} until @pierpont == $max;
@pierpont;
}
my @pierpont_1st = pierpont(250,1);
my @pierpont_2nd = pierpont(250,2);
say "First 50 Pierpont primes of the first kind:";
my $fmt = "%9d"x10 . "\n";
for my $row (0..4) { printf $fmt, map { $pierpont_1st[10*$row + $_] } 0..9 }
say "\nFirst 50 Pierpont primes of the second kind:";
for my $row (0..4) { printf $fmt, map { $pierpont_2nd[10*$row + $_] } 0..9 }
say "\n250th Pierpont prime of the first kind: " . $pierpont_1st[249];
say "\n250th Pierpont prime of the second kind: " . $pierpont_2nd[249]; | 433Pierpont primes
| 2perl
| 0r4s4 |
(ns derangements.core
(:require [clojure.set:as s]))
(defn subfactorial [n]
(case n
0 1
1 0
(* (dec n) (+ (subfactorial (dec n)) (subfactorial (- n 2))))))
(defn no-fixed-point
"f: A -> B must be a biyective function written as a hash-map, returns
all g: A -> B such that (f(a) = b) => not(g(a) = b)"
[f]
(case (count f)
0 [{}]
1 []
(let [g (s/map-invert f)
a (first (keys f))
a' (f a)]
(mapcat
(fn [b'] (let [b (g b')
f' (dissoc f a b)]
(concat (map #(reduce conj % [[a b'] [b a']])
(no-fixed-point f'))
(map #(conj % [a b'])
(no-fixed-point (assoc f' b a'))))))
(filter #(not= a' %) (keys g))))))
(defn derangements [xs]
{:pre [(= (count xs) (count (set xs)))]}
(map (fn [f] (mapv f xs))
(no-fixed-point (into {} (map vector xs xs)))))
(defn -main []
(do
(doall (map println (derangements [0,1,2,3])))
(doall (map #(println (str (subfactorial %) " " (count (derangements (range %)))))
(range 10)))
(println (subfactorial 20)))) | 444Permutations/Derangements
| 6clojure
| ojy8j |
double run_test(double p, int len, int runs)
{
int r, x, y, i, cnt = 0, thresh = p * RAND_MAX;
for (r = 0; r < runs; r++)
for (x = 0, i = len; i--; x = y)
cnt += x < (y = rand() < thresh);
return (double)cnt / runs / len;
}
int main(void)
{
double p, p1p, K;
int ip, n;
puts(
);
for (ip = 1; ip < 10; ip += 2) {
p = ip / 10., p1p = p * (1 - p);
for (n = 100; n <= 100000; n *= 10) {
K = run_test(p, n, 1000);
printf(,
p, n, K, p1p, K - p1p, (K - p1p) / p1p * 100);
}
putchar('\n');
}
return 0;
} | 447Percolation/Mean run density
| 5c
| unjv4 |
char *cell, *start, *end;
int m, n;
void make_grid(int x, int y, double p)
{
int i, j, thresh = p * RAND_MAX;
m = x, n = y;
end = start = realloc(start, (x+1) * (y+1) + 1);
memset(start, 0, m + 1);
cell = end = start + m + 1;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
*end++ = rand() < thresh ? '+' : '.';
*end++ = '\n';
}
end[-1] = 0;
end -= ++m;
}
int ff(char *p)
{
if (*p != '+') return 0;
*p = '
return p >= end || ff(p+m) || ff(p+1) || ff(p-1) || ff(p-m);
}
int percolate(void)
{
int i;
for (i = 0; i < m && !ff(cell + i); i++);
return i < m;
}
int main(void)
{
make_grid(15, 15, .5);
percolate();
puts();
puts(cell);
puts();
double p;
int ip, i, cnt;
for (ip = 0; ip <= 10; ip++) {
p = ip / 10.;
for (cnt = i = 0; i < 10000; i++) {
make_grid(15, 15, p);
cnt += percolate();
}
printf(, p, cnt / 10000.);
}
return 0;
} | 448Percolation/Site percolation
| 5c
| gtk45 |
use strict;
use warnings; no warnings 'uninitialized';
use feature 'say';
use List::Util <sum head>;
sub divmod { int $_[0]/$_[1], $_[0]%$_[1] }
my $b = 18;
my(@offset,@span,$cnt);
push @span, ($cnt++) x $_ for <1 3 8 44 15 17 15 15>;
@offset = (16, 10, 10, (2*$b)+1, (-2*$b)-15, (2*$b)+1, (-2*$b)-15);
for my $n (<1 2 29 42 57 58 72 89 90 103 118>) {
printf "%3d:%2d,%2d\n", $n, map { $_+1 } divmod $n-1 + sum(head $span[$n-1], @offset), $b;
} | 446Periodic table
| 2perl
| gtp4e |
import java.util.*;
public class PigDice {
public static void main(String[] args) {
final int maxScore = 100;
final int playerCount = 2;
final String[] yesses = {"y", "Y", ""};
int[] safeScore = new int[2];
int player = 0, score = 0;
Scanner sc = new Scanner(System.in);
Random rnd = new Random();
while (true) {
System.out.printf(" Player%d: (%d,%d) Rolling? (y/n) ", player,
safeScore[player], score);
if (safeScore[player] + score < maxScore
&& Arrays.asList(yesses).contains(sc.nextLine())) {
final int rolled = rnd.nextInt(6) + 1;
System.out.printf(" Rolled%d\n", rolled);
if (rolled == 1) {
System.out.printf(" Bust! You lose%d but keep%d\n\n",
score, safeScore[player]);
} else {
score += rolled;
continue;
}
} else {
safeScore[player] += score;
if (safeScore[player] >= maxScore)
break;
System.out.printf(" Sticking with%d\n\n", safeScore[player]);
}
score = 0;
player = (player + 1) % playerCount;
}
System.out.printf("\n\nPlayer%d wins with a score of%d",
player, safeScore[player]);
}
} | 434Pig the dice game
| 9java
| nk7ih |
class Permutation
include Enumerable
attr_reader :num_elements, :size
def initialize(num_elements)
@num_elements = num_elements
@size = fact(num_elements)
end
def each
return self.to_enum unless block_given?
(0...@size).each{|i| yield unrank(i)}
end
def unrank(r)
pi = (0...num_elements).to_a
(@num_elements-1).downto(1) do |n|
s, r = r.divmod(fact(n))
pi[n], pi[s] = pi[s], pi[n]
end
pi
end
def rank(pi)
pi = pi.dup
pi1 = pi.zip(0...pi.size).sort.map(&:last)
(pi.size-1).downto(0).inject(0) do |memo,i|
pi[i], pi[pi1[i]] = pi[pi1[i]], (s = pi[i])
pi1[s], pi1[i] = pi1[i], pi1[s]
memo += s * fact(i)
end
end
private
def fact(n)
n.zero?? 1: n.downto(1).inject(:*)
end
end | 435Permutations/Rank of a permutation
| 14ruby
| rzngs |
package main
import "fmt"
var tr = []int{85, 88, 75, 66, 25, 29, 83, 39, 97}
var ct = []int{68, 41, 10, 49, 16, 65, 32, 92, 28, 98}
func main() { | 440Permutation test
| 0go
| j687d |
let players = [
{ name: '', score: 0 },
{ name: '', score: 0 }
];
let curPlayer = 1,
gameOver = false;
players[0].name = prompt('Your name, player #1:').toUpperCase();
players[1].name = prompt('Your name, player #2:').toUpperCase();
function roll() { return 1 + Math.floor(Math.random()*6) }
function round(player) {
let curSum = 0,
quit = false,
dice;
alert(`It's ${player.name}'s turn (${player.score}).`);
while (!quit) {
dice = roll();
if (dice == 1) {
alert('You roll a 1. What a pity!');
quit = true;
} else {
curSum += dice;
quit = !confirm(`
You roll a ${dice} (sum: ${curSum}).\n
Roll again?
`);
if (quit) {
player.score += curSum;
if (player.score >= 100) gameOver = true;
}
}
}
} | 434Pig the dice game
| 10javascript
| 3epz0 |
import scala.math._
def factorial(n: Int): BigInt = {
(1 to n).map(BigInt.apply).fold(BigInt(1))(_ * _)
}
def indexToPermutation(n: Int, x: BigInt): List[Int] = {
indexToPermutation((0 until n).toList, x)
}
def indexToPermutation(ns: List[Int], x: BigInt): List[Int] = ns match {
case Nil => Nil
case _ => {
val (iBig, xNew) = x /% factorial(ns.size - 1)
val i = iBig.toInt
ns(i) :: indexToPermutation(ns.take(i) ++ ns.drop(i + 1), xNew)
}
}
def permutationToIndex[A](xs: List[A])(implicit ord: Ordering[A]): BigInt = xs match {
case Nil => BigInt(0)
case x :: rest => factorial(rest.size) * rest.count(ord.lt(_, x)) + permutationToIndex(rest)
} | 435Permutations/Rank of a permutation
| 16scala
| kmzhk |
binomial n m = (f !! n) `div` (f !! m) `div` (f !! (n - m))
where f = scanl (*) 1 [1..]
permtest treat ctrl = (fromIntegral less) / (fromIntegral total) * 100
where
total = binomial (length avail) (length treat)
less = combos (sum treat) (length treat) avail
avail = ctrl ++ treat
combos total n a@(x:xs)
| total < 0 = binomial (length a) n
| n == 0 = 0
| n > length a = 0
| n == length a = fromEnum (total < sum a)
| otherwise = combos (total - x) (n - 1) xs
+ combos total n xs
main = let r = permtest
[85, 88, 75, 66, 25, 29, 83, 39, 97]
[68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
in do putStr ">: "; print r
putStr "<=: "; print $ 100 - r | 440Permutation test
| 8haskell
| ojl8p |
int *map, w, ww;
void make_map(double p)
{
int i, thresh = RAND_MAX * p;
i = ww = w * w;
map = realloc(map, i * sizeof(int));
while (i--) map[i] = -(rand() < thresh);
}
char alpha[] =
;
void show_cluster(void)
{
int i, j, *s = map;
for (i = 0; i < w; i++) {
for (j = 0; j < w; j++, s++)
printf(, *s < ALEN ? alpha[1 + *s] : '?');
putchar('\n');
}
}
void recur(int x, int v) {
if (x >= 0 && x < ww && map[x] == -1) {
map[x] = v;
recur(x - w, v);
recur(x - 1, v);
recur(x + 1, v);
recur(x + w, v);
}
}
int count_clusters(void)
{
int i, cls;
for (cls = i = 0; i < ww; i++) {
if (-1 != map[i]) continue;
recur(i, ++cls);
}
return cls;
}
double tests(int n, double p)
{
int i;
double k;
for (k = i = 0; i < n; i++) {
make_map(p);
k += (double)count_clusters() / ww;
}
return k / n;
}
int main(void)
{
w = 15;
make_map(.5);
printf(, count_clusters());
show_cluster();
printf();
for (w = 1<<2; w <= 1<<14; w<<=2)
printf(, w, tests(5, .5));
free(map);
return 0;
} | 449Percolation/Mean cluster density
| 5c
| 2o4lo |
long totient(long n){
long tot = n,i;
for(i=2;i*i<=n;i+=2){
if(n%i==0){
while(n%i==0)
n/=i;
tot-=tot/i;
}
if(i==2)
i=1;
}
if(n>1)
tot-=tot/n;
return tot;
}
long* perfectTotients(long n){
long *ptList = (long*)malloc(n*sizeof(long)), m,count=0,sum,tot;
for(m=1;count<n;m++){
tot = m;
sum = 0;
while(tot != 1){
tot = totient(tot);
sum += tot;
}
if(sum == m)
ptList[count++] = m;
}
return ptList;
}
long main(long argC, char* argV[])
{
long *ptList,i,n;
if(argC!=2)
printf(,argV[0]);
else{
n = atoi(argV[1]);
ptList = perfectTotients(n);
printf(,n);
for(i=0;i<n;i++)
printf(,ptList[i]);
printf();
}
return 0;
} | 450Perfect totient numbers
| 5c
| nkti6 |
def perta(atomic) -> (int, int):
NOBLES = 2, 10, 18, 36, 54, 86, 118
INTERTWINED = 0, 0, 0, 0, 0, 57, 89
INTERTWINING_SIZE = 14
LINE_WIDTH = 18
prev_noble = 0
for row, noble in enumerate(NOBLES):
if atomic <= noble:
nb_elem = noble - prev_noble
rank = atomic - prev_noble
if INTERTWINED[row] and INTERTWINED[row] <= atomic <= INTERTWINED[row] + INTERTWINING_SIZE:
row += 2
col = rank + 1
else:
nb_empty = LINE_WIDTH - nb_elem
inside_left_element_rank = 2 if noble > 2 else 1
col = rank + (nb_empty if rank > inside_left_element_rank else 0)
break
prev_noble = noble
return row+1, col
TESTS = {
1: (1, 1),
2: (1, 18),
29: (4,11),
42: (5, 6),
58: (8, 5),
59: (8, 6),
57: (8, 4),
71: (8, 18),
72: (6, 4),
89: (9, 4),
90: (9, 5),
103: (9, 18),
}
for input, out in TESTS.items():
found = perta(input)
print('TEST:{:3d} -> '.format(input) + str(found) + (f'; ERROR: expected {out}' if found != out else '')) | 446Periodic table
| 3python
| rz1gq |
import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
def pierpont(ulim, vlim, first):
p = 0
p2 = 1
p3 = 1
pp = []
for v in xrange(vlim):
for u in xrange(ulim):
p = p2 * p3
if first:
p = p + 1
else:
p = p - 1
if is_Prime(p):
pp.append(p)
p2 = p2 * 2
p3 = p3 * 3
p2 = 1
pp.sort()
return pp
def main():
print
pp = pierpont(120, 80, True)
for i in xrange(50):
print % pp[i],
if (i - 9)% 10 == 0:
print
print
pp2 = pierpont(120, 80, False)
for i in xrange(50):
print % pp2[i],
if (i - 9)% 10 == 0:
print
print , pp[249]
print , pp2[249]
main() | 433Pierpont primes
| 3python
| 87g0o |
package main
import (
"fmt"
"strings"
)
const phrase = "rosetta code phrase reversal"
func revStr(s string) string {
rs := make([]rune, len(s))
i := len(s)
for _, r := range s {
i--
rs[i] = r
}
return string(rs[i:])
}
func main() {
fmt.Println("Reversed: ", revStr(phrase))
ws := strings.Fields(phrase)
for i, w := range ws {
ws[i] = revStr(w)
}
fmt.Println("Words reversed: ", strings.Join(ws, " "))
ws = strings.Fields(phrase)
last := len(ws) - 1
for i, w := range ws[:len(ws)/2] {
ws[i], ws[last-i] = ws[last-i], w
}
fmt.Println("Word order reversed:", strings.Join(ws, " "))
} | 437Phrase reversals
| 0go
| pczbg |
public class PermutationTest {
private static final int[] data = new int[]{
85, 88, 75, 66, 25, 29, 83, 39, 97,
68, 41, 10, 49, 16, 65, 32, 92, 28, 98
};
private static int pick(int at, int remain, int accu, int treat) {
if (remain == 0) return (accu > treat) ? 1 : 0;
return pick(at - 1, remain - 1, accu + data[at - 1], treat)
+ ((at > remain) ? pick(at - 1, remain, accu, treat) : 0);
}
public static void main(String[] args) {
int treat = 0;
double total = 1.0;
for (int i = 0; i <= 8; ++i) {
treat += data[i];
}
for (int i = 19; i >= 11; --i) {
total *= i;
}
for (int i = 9; i >= 1; --i) {
total /= i;
}
int gt = pick(19, 9, 0, treat);
int le = (int) (total - gt);
System.out.printf("<=:%f%% %d\n", 100.0 * le / total, le);
System.out.printf(" >:%f%% %d\n", 100.0 * gt / total, gt);
}
} | 440Permutation test
| 9java
| wu3ej |
typedef unsigned int c_t;
c_t *cells, *start, *end;
int m, n;
void make_grid(double p, int x, int y)
{
int i, j, thresh = RAND_MAX * p;
m = x, n = y;
start = realloc(start, m * (n + 2) * sizeof(c_t));
cells = start + m;
for (i = 0; i < m; i++)
start[i] = BWALL | RWALL;
for (i = 0, end = cells; i < y; i++) {
for (j = x; --j; )
*end++ = (rand() < thresh ? BWALL : 0)
|(rand() < thresh ? RWALL : 0);
*end++ = RWALL | (rand() < thresh ? BWALL: 0);
}
memset(end, 0, sizeof(c_t) * m);
}
void show_grid(void)
{
int i, j;
for (j = 0; j < m; j++) printf();
puts();
for (i = 0; i <= n; i++) {
putchar(i == n ? ' ' : '|');
for (j = 0; j < m; j++) {
printf((cells[i*m + j] & FILL) ? : );
putchar((cells[i*m + j] & RWALL) ? '|' : ' ');
}
putchar('\n');
if (i == n) return;
for (j = 0; j < m; j++)
printf((cells[i*m + j] & BWALL) ? : );
puts();
}
}
int fill(c_t *p)
{
if ((*p & FILL)) return 0;
*p |= FILL;
if (p >= end) return 1;
return ( !(p[ 0] & BWALL) && fill(p + m) ) ||
( !(p[ 0] & RWALL) && fill(p + 1) ) ||
( !(p[-1] & RWALL) && fill(p - 1) ) ||
( !(p[-m] & BWALL) && fill(p - m) );
}
int percolate(void)
{
int i;
for (i = 0; i < m && !fill(cells + i); i++);
return i < m;
}
int main(void)
{
make_grid(.5, 10, 10);
percolate();
show_grid();
int cnt, i, p;
puts();
for (p = 1; p < 10; p++) {
for (cnt = i = 0; i < 10000; i++) {
make_grid(p / 10., 10, 10);
cnt += percolate();
}
printf(, p / 10., (double)cnt / i);
}
free(start);
return 0;
} | 451Percolation/Bond percolation
| 5c
| j6k70 |
null | 434Pig the dice game
| 11kotlin
| sguq7 |
package main
import (
"fmt"
"math/rand"
"time"
)
var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(list[rand.Intn(len(list))])
} | 436Pick random element
| 0go
| kmthz |
def list = [25, 30, 1, 450, 3, 78]
def random = new Random();
(0..3).each {
def i = random.nextInt(list.size())
println "list[${i}] == ${list[i]}"
} | 436Pick random element
| 7groovy
| gto46 |
def phaseReverse = { text, closure -> closure(text.split(/ /)).join(' ')}
def text = 'rosetta code phrase reversal'
println "Original: $text"
println "Reversed: ${phaseReverse(text) { it.reverse().collect { it.reverse() } } }"
println "Reversed Words: ${phaseReverse(text) { it.collect { it.reverse() } } }"
println "Reversed Order: ${phaseReverse(text) { it.reverse() } }" | 437Phrase reversals
| 7groovy
| 73irz |
package permute | 442Permutations by swapping
| 0go
| 73qr2 |
null | 440Permutation test
| 11kotlin
| b9nkb |
package main
import (
"bytes"
"fmt"
"math/rand"
"time"
)
func main() {
const (
m, n = 15, 15
t = 1e4
minp, maxp, p = 0, 1, 0.1
)
rand.Seed(2) | 448Percolation/Site percolation
| 0go
| ihzog |
const int kDecks[N_DECKS] = { 8, 24, 52, 100, 1020, 1024, 10000 };
int CreateDeck( int **deck, int nCards );
void InitDeck( int *deck, int nCards );
int DuplicateDeck( int **dest, const int *orig, int nCards );
int InitedDeck( int *deck, int nCards );
int ShuffleDeck( int *deck, int nCards );
void FreeDeck( int **deck );
int main() {
int i, nCards, nShuffles;
int *deck = NULL;
for( i=0; i<N_DECKS; ++i ) {
nCards = kDecks[i];
if( !CreateDeck(&deck,nCards) ) {
fprintf( stderr, );
return 1;
}
InitDeck( deck, nCards );
nShuffles = 0;
do {
ShuffleDeck( deck, nCards );
++nShuffles;
} while( !InitedDeck(deck,nCards) );
printf( , nCards, nShuffles );
FreeDeck( &deck );
}
return 0;
}
int CreateDeck( int **deck, int nCards ) {
int *tmp = NULL;
if( deck != NULL )
tmp = malloc( nCards*sizeof(*tmp) );
return tmp!=NULL ? (*deck=tmp)!=NULL : 0;
}
void InitDeck( int *deck, int nCards ) {
if( deck != NULL ) {
int i;
for( i=0; i<nCards; ++i )
deck[i] = i;
}
}
int DuplicateDeck( int **dest, const int *orig, int nCards ) {
if( orig != NULL && CreateDeck(dest,nCards) ) {
memcpy( *dest, orig, nCards*sizeof(*orig) );
return 1;
}
else {
return 0;
}
}
int InitedDeck( int *deck, int nCards ) {
int i;
for( i=0; i<nCards; ++i )
if( deck[i] != i )
return 0;
return 1;
}
int ShuffleDeck( int *deck, int nCards ) {
int *copy = NULL;
if( DuplicateDeck(©,deck,nCards) ) {
int i, j;
for( i=j=0; i<nCards/2; ++i, j+=2 ) {
deck[j] = copy[i];
deck[j+1] = copy[i+nCards/2];
}
FreeDeck( © );
return 1;
}
else {
return 0;
}
}
void FreeDeck( int **deck ) {
if( *deck != NULL ) {
free( *deck );
*deck = NULL;
}
} | 452Perfect shuffle
| 5c
| a2e11 |
local numPlayers = 2
local maxScore = 100
local scores = { }
for i = 1, numPlayers do
scores[i] = 0 | 434Pig the dice game
| 1lua
| 0r5sd |
reverseString, reverseEachWord, reverseWordOrder :: String -> String
reverseString = reverse
reverseEachWord = wordLevel (fmap reverse)
reverseWordOrder = wordLevel reverse
wordLevel :: ([String] -> [String]) -> String -> String
wordLevel f = unwords . f . words
main :: IO ()
main =
(putStrLn . unlines) $
[reverseString, reverseEachWord, reverseWordOrder] <*>
["rosetta code phrase reversal"] | 437Phrase reversals
| 8haskell
| fprd1 |
sPermutations :: [a] -> [([a], Int)]
sPermutations = flip zip (cycle [-1, 1]) . foldr aux [[]]
where
aux x items = do
(f, item) <- zip (repeat id) items
f (insertEv x item)
insertEv x [] = [[x]]
insertEv x l@(y:ys) = (x: l): ((y:) <$> insertEv x ys)
main :: IO ()
main = do
putStrLn "3 items:"
mapM_ print $ sPermutations [1 .. 3]
putStrLn "\n4 items:"
mapM_ print $ sPermutations [1 .. 4] | 442Permutations by swapping
| 8haskell
| 87m0z |
int main(int argc, char **argv)
{
image im1, im2;
double totalDiff = 0.0;
unsigned int x, y;
if ( argc < 3 )
{
fprintf(stderr, , argv[0]);
exit(1);
}
im1 = read_image(argv[1]);
if ( im1 == NULL ) exit(1);
im2 = read_image(argv[2]);
if ( im2 == NULL ) { free_img(im1); exit(1); }
if ( (im1->width != im2->width) || (im1->height != im2->height) )
{
fprintf(stderr, );
} else {
for(x=0; x < im1->width; x++)
{
for(y=0; y < im1->width; y++)
{
totalDiff += fabs( GET_PIXEL(im1, x, y)[RED_C] - GET_PIXEL(im2, x, y)[RED_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[GREEN_C] - GET_PIXEL(im2, x, y)[GREEN_C] ) / 255.0;
totalDiff += fabs( GET_PIXEL(im1, x, y)[BLUE_C] - GET_PIXEL(im2, x, y)[BLUE_C] ) / 255.0;
}
}
printf(, 100.0 * totalDiff / (double)(im1->width * im1->height * 3) );
}
free_img(im1);
free_img(im2);
} | 453Percentage difference between images
| 5c
| ihio2 |
package main
import (
"fmt"
"math/rand"
"time"
)
var (
n_range = []int{4, 64, 256, 1024, 4096}
M = 15
N = 15
)
const (
p = .5
t = 5
NOT_CLUSTERED = 1
cell2char = " #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
func newgrid(n int, p float64) [][]int {
g := make([][]int, n)
for y := range g {
gy := make([]int, n)
for x := range gy {
if rand.Float64() < p {
gy[x] = 1
}
}
g[y] = gy
}
return g
}
func pgrid(cell [][]int) {
for n := 0; n < N; n++ {
fmt.Print(n%10, ") ")
for m := 0; m < M; m++ {
fmt.Printf("%c", cell2char[cell[n][m]])
}
fmt.Println()
}
}
func cluster_density(n int, p float64) float64 {
cc := clustercount(newgrid(n, p))
return float64(cc) / float64(n) / float64(n)
}
func clustercount(cell [][]int) int {
walk_index := 1
for n := 0; n < N; n++ {
for m := 0; m < M; m++ {
if cell[n][m] == NOT_CLUSTERED {
walk_index++
walk_maze(m, n, cell, walk_index)
}
}
}
return walk_index - 1
}
func walk_maze(m, n int, cell [][]int, indx int) {
cell[n][m] = indx
if n < N-1 && cell[n+1][m] == NOT_CLUSTERED {
walk_maze(m, n+1, cell, indx)
}
if m < M-1 && cell[n][m+1] == NOT_CLUSTERED {
walk_maze(m+1, n, cell, indx)
}
if m > 0 && cell[n][m-1] == NOT_CLUSTERED {
walk_maze(m-1, n, cell, indx)
}
if n > 0 && cell[n-1][m] == NOT_CLUSTERED {
walk_maze(m, n-1, cell, indx)
}
}
func main() {
rand.Seed(time.Now().Unix())
cell := newgrid(N, .5)
fmt.Printf("Found%d clusters in this%d by%d grid\n\n",
clustercount(cell), N, N)
pgrid(cell)
fmt.Println()
for _, n := range n_range {
M = n
N = n
sum := 0.
for i := 0; i < t; i++ {
sum += cluster_density(n, p)
}
sim := sum / float64(t)
fmt.Printf("t=%3d p=%4.2f n=%5d sim=%7.5f\n", t, p, n, sim)
}
} | 449Percolation/Mean cluster density
| 0go
| q4oxz |
import Control.Monad
import Control.Monad.Random
import Data.Array.Unboxed
import Data.List
import Formatting
type Field = UArray (Int, Int) Char
percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)])
percolateR [] f = (f, [])
percolateR seep f =
let ((xLo,yLo),(xHi,yHi)) = bounds f
validSeep = filter (\p@(x,y) -> x >= xLo
&& x <= xHi
&& y >= yLo
&& y <= yHi
&& f!p == ' ') $ nub $ sort seep
neighbors (x,y) = [(x,y-1), (x,y+1), (x-1,y), (x+1,y)]
in percolateR
(concatMap neighbors validSeep)
(f // map (\p -> (p,'.')) validSeep)
percolate :: Field -> Field
percolate start =
let ((_,_),(xHi,_)) = bounds start
(final, _) = percolateR [(x,0) | x <- [0..xHi]] start
in final
initField :: Int -> Int -> Double -> Rand StdGen Field
initField w h threshold = do
frnd <- fmap (\rv -> if rv<threshold then ' ' else '#') <$> getRandoms
return $ listArray ((0,0), (w-1, h-1)) frnd
leaks :: Field -> [Bool]
leaks f =
let ((xLo,_),(xHi,yHi)) = bounds f
in [f!(x,yHi)=='.'| x <- [xLo..xHi]]
oneTest :: Int -> Int -> Double -> Rand StdGen Bool
oneTest w h threshold =
or.leaks.percolate <$> initField w h threshold
multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double
multiTest testCount w h threshold = do
results <- replicateM testCount $ oneTest w h threshold
let leakyCount = length $ filter id results
return $ fromIntegral leakyCount / fromIntegral testCount
showField :: Field -> IO ()
showField a = do
let ((xLo,yLo),(xHi,yHi)) = bounds a
mapM_ print [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]]
main :: IO ()
main = do
g <- getStdGen
let w = 15
h = 15
threshold = 0.6
(startField, g2) = runRand (initField w h threshold) g
putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.")
putStrLn ""
showField startField
putStrLn ""
putStrLn "Same field after percolation."
putStrLn ""
showField $ percolate startField
let testCount = 10000
densityCount = 10
putStrLn ""
putStrLn ( "Results of running percolation test " ++ show testCount
++ " times with thresholds ranging from 0/" ++ show densityCount
++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .")
let densities = [0..densityCount]
tests = sequence [multiTest testCount w h v
| density <- densities,
let v = fromIntegral density / fromIntegral densityCount ]
results = zip densities (evalRand tests g2)
mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results] | 448Percolation/Site percolation
| 8haskell
| vir2k |
import System.Random (randomRIO)
pick :: [a] -> IO a
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)
x <- pick [1, 2, 3] | 436Pick random element
| 8haskell
| nkgie |
use warnings;
use strict;
use List::Util qw{ sum };
sub means {
my @groups = @_;
return map sum(@$_) / @$_, @groups;
}
sub following {
my $pattern = shift;
my $orig_count = grep $_, @$pattern;
my $count;
do {
my $i = $
until (0 > $i) {
$pattern->[$i] = $pattern->[$i] ? 0 : 1;
last if $pattern->[$i];
--$i;
}
$count = grep $_, @$pattern;
} until $count == $orig_count or not $count;
undef @$pattern unless $count;
}
my @groups;
my $i = 0;
while (<DATA>) {
chomp;
$i++, next if /^$/;
push @{ $groups[$i] }, $_;
}
my @orig_means = means(@groups);
my $orig_cmp = $orig_means[0] - $orig_means[1];
my $pattern = [ (0) x @{ $groups[0] },
(1) x @{ $groups[1] }
];
my @cmp = (0) x 3;
while (@$pattern) {
my @perms = map { my $g = $_;
[ (@{ $groups[0] }, @{ $groups[1] } ) [ grep $pattern->[$_] == $g, 0 .. $
} 0, 1;
my @means = means(@perms);
$cmp[ ($means[0] - $means[1]) <=> $orig_cmp ]++;
} continue {
following($pattern);
}
my $all = sum(@cmp);
my $length = length $all;
for (0, -1, 1) {
printf "%-7s%${length}d%6.3f%%\n",
(qw(equal greater less))[$_], $cmp[$_], 100 * $cmp[$_] / $all;
}
__DATA__
85
88
75
66
25
29
83
39
97
68
41
10
49
16
65
32
92
28
98 | 440Permutation test
| 2perl
| 6w736 |
import Data.List
import Data.Maybe
import System.Random
import Control.Monad.State
import Text.Printf
import Data.Set (Set)
import qualified Data.Set as S
type Matrix = [[Bool]]
type Cell = (Int, Int)
type Cluster = Set (Int, Int)
clusters :: Matrix -> [Cluster]
clusters m = unfoldr findCuster cells
where
cells = S.fromList [ (i,j) | (r, i) <- zip m [0..]
, (x, j) <- zip r [0..], x]
findCuster s = do
(p, ps) <- S.minView s
return $ runState (expand p) ps
expand p = do
ns <- state $ extract (neigbours p)
xs <- mapM expand $ S.elems ns
return $ S.insert p $ mconcat xs
extract s1 s2 = (s2 `S.intersection` s1, s2 S.\\ s1)
neigbours (i,j) = S.fromList [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
n = length m
showClusters :: Matrix -> String
showClusters m = unlines [ unwords [ mark (i,j)
| j <- [0..n-1] ]
| i <- [0..n-1] ]
where
cls = clusters m
n = length m
mark c = maybe "." snd $ find (S.member c . fst) $ zip cls syms
syms = sequence [['a'..'z'] ++ ['A'..'Z']]
randomMatrices :: Int -> StdGen -> [Matrix]
randomMatrices n = clipBy n . clipBy n . randoms
where
clipBy n = unfoldr (Just . splitAt n)
randomMatrix n = head . randomMatrices n
tests :: Int -> StdGen -> [Int]
tests n = map (length . clusters) . randomMatrices n
task :: Int -> StdGen -> (Int, Double)
task n g = (n, result)
where
result = mean $ take 10 $ map density $ tests n g
density c = fromIntegral c / fromIntegral n**2
mean lst = sum lst / genericLength lst
main = newStdGen >>= mapM_ (uncurry (printf "%d\t%.5f\n")) . res
where
res = mapM task [10,50,100,500] | 449Percolation/Mean cluster density
| 8haskell
| mq2yf |
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main() {
const (
m, n = 10, 10
t = 1000
minp, maxp, p = 0.1, 0.99, 0.1
) | 451Percolation/Bond percolation
| 0go
| fpzd0 |
package main
import (
"fmt"
"math/rand"
)
var (
pList = []float64{.1, .3, .5, .7, .9}
nList = []int{1e2, 1e3, 1e4, 1e5}
t = 100
)
func main() {
for _, p := range pList {
theory := p * (1 - p)
fmt.Printf("\np:%.4f theory:%.4f t:%d\n", p, theory, t)
fmt.Println(" n sim sim-theory")
for _, n := range nList {
sum := 0
for i := 0; i < t; i++ {
run := false
for j := 0; j < n; j++ {
one := rand.Float64() < p
if one && !run {
sum++
}
run = one
}
}
K := float64(sum) / float64(t) / float64(n)
fmt.Printf("%9d%15.4f%9.6f\n", n, K, K-theory)
}
}
} | 447Percolation/Mean run density
| 0go
| 0rfsk |
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(noise(3.14, 42, 7))
}
func noise(x, y, z float64) float64 {
X := int(math.Floor(x)) & 255
Y := int(math.Floor(y)) & 255
Z := int(math.Floor(z)) & 255
x -= math.Floor(x)
y -= math.Floor(y)
z -= math.Floor(z)
u := fade(x)
v := fade(y)
w := fade(z)
A := p[X] + Y
AA := p[A] + Z
AB := p[A+1] + Z
B := p[X+1] + Y
BA := p[B] + Z
BB := p[B+1] + Z
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], x-1, y, z)),
lerp(u, grad(p[AB], x, y-1, z),
grad(p[BB], x-1, y-1, z))),
lerp(v, lerp(u, grad(p[AA+1], x, y, z-1),
grad(p[BA+1], x-1, y, z-1)),
lerp(u, grad(p[AB+1], x, y-1, z-1),
grad(p[BB+1], x-1, y-1, z-1))))
}
func fade(t float64) float64 { return t * t * t * (t*(t*6-15) + 10) }
func lerp(t, a, b float64) float64 { return a + t*(b-a) }
func grad(hash int, x, y, z float64) float64 { | 445Perlin noise
| 0go
| 1l8p5 |
package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
var perfect []int
for n := 1; len(perfect) < 20; n += 2 {
tot := n
sum := 0
for tot != 1 {
tot = totient(tot)
sum += tot
}
if sum == n {
perfect = append(perfect, n)
}
}
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
} | 450Perfect totient numbers
| 0go
| rzhgm |
require 'gmp'
def smooth_generator(ar)
return to_enum(__method__, ar) unless block_given?
next_smooth = 1
queues = ar.map{|num| [num, []] }
loop do
yield next_smooth
queues.each {|m, queue| queue << next_smooth * m}
next_smooth = queues.collect{|m, queue| queue.first}.min
queues.each{|m, queue| queue.shift if queue.first == next_smooth }
end
end
def pierpont(num = 1)
return to_enum(__method__, num) unless block_given?
smooth_generator([2,3]).each{|smooth| yield smooth+num if GMP::Z(smooth + num).probab_prime? > 0}
end
def puts_cols(ar, n=10)
ar.each_slice(n).map{|slice|puts slice.map{|n| n.to_s.rjust(10)}.join }
end
n, m = 50, 250
puts
puts_cols(pierpont.take(n))
puts ,
puts
puts_cols(pierpont(-1).take(n))
puts | 433Pierpont primes
| 14ruby
| ih7oh |
import java.util.Arrays;
public class PhraseRev{
private static String reverse(String x){
return new StringBuilder(x).reverse().toString();
}
private static <T> T[] reverse(T[] x){
T[] rev = Arrays.copyOf(x, x.length);
for(int i = x.length - 1; i >= 0; i--){
rev[x.length - 1 - i] = x[i];
}
return rev;
}
private static String join(String[] arr, String joinStr){
StringBuilder joined = new StringBuilder();
for(int i = 0; i < arr.length; i++){
joined.append(arr[i]);
if(i < arr.length - 1) joined.append(joinStr);
}
return joined.toString();
}
public static void main(String[] args){
String str = "rosetta code phrase reversal";
System.out.println("Straight-up reversed: " + reverse(str));
String[] words = str.split(" ");
for(int i = 0; i < words.length; i++){
words[i] = reverse(words[i]);
}
System.out.println("Reversed words: " + join(words, " "));
System.out.println("Reversed word order: " + join(reverse(str.split(" ")), " "));
}
} | 437Phrase reversals
| 9java
| 0r2se |
package org.rosettacode.java;
import java.util.Arrays;
import java.util.stream.IntStream;
public class HeapsAlgorithm {
public static void main(String[] args) {
Object[] array = IntStream.range(0, 4)
.boxed()
.toArray();
HeapsAlgorithm algorithm = new HeapsAlgorithm();
algorithm.recursive(array);
System.out.println();
algorithm.loop(array);
}
void recursive(Object[] array) {
recursive(array, array.length, true);
}
void recursive(Object[] array, int n, boolean plus) {
if (n == 1) {
output(array, plus);
} else {
for (int i = 0; i < n; i++) {
recursive(array, n - 1, i == 0);
swap(array, n % 2 == 0 ? i : 0, n - 1);
}
}
}
void output(Object[] array, boolean plus) {
System.out.println(Arrays.toString(array) + (plus ? " +1" : " -1"));
}
void swap(Object[] array, int a, int b) {
Object o = array[a];
array[a] = array[b];
array[b] = o;
}
void loop(Object[] array) {
loop(array, array.length);
}
void loop(Object[] array, int n) {
int[] c = new int[n];
output(array, true);
boolean plus = false;
for (int i = 0; i < n; ) {
if (c[i] < i) {
if (i % 2 == 0) {
swap(array, 0, i);
} else {
swap(array, c[i], i);
}
output(array, plus);
plus = !plus;
c[i]++;
i = 0;
} else {
c[i] = 0;
i++;
}
}
}
} | 442Permutations by swapping
| 9java
| evfa5 |
package main
import (
"fmt"
"math/rand"
"time"
)
var F = [][]int{
{1, -1, 1, 0, 1, 1, 2, 1}, {0, 1, 1, -1, 1, 0, 2, 0},
{1, 0, 1, 1, 1, 2, 2, 1}, {1, 0, 1, 1, 2, -1, 2, 0},
{1, -2, 1, -1, 1, 0, 2, -1}, {0, 1, 1, 1, 1, 2, 2, 1},
{1, -1, 1, 0, 1, 1, 2, -1}, {1, -1, 1, 0, 2, 0, 2, 1},
}
var I = [][]int{{0, 1, 0, 2, 0, 3, 0, 4}, {1, 0, 2, 0, 3, 0, 4, 0}}
var L = [][]int{
{1, 0, 1, 1, 1, 2, 1, 3}, {1, 0, 2, 0, 3, -1, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 3}, {0, 1, 1, 0, 2, 0, 3, 0}, {0, 1, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 0, 3, 1, 0}, {1, 0, 2, 0, 3, 0, 3, 1}, {1, -3, 1, -2, 1, -1, 1, 0},
}
var N = [][]int{
{0, 1, 1, -2, 1, -1, 1, 0}, {1, 0, 1, 1, 2, 1, 3, 1},
{0, 1, 0, 2, 1, -1, 1, 0}, {1, 0, 2, 0, 2, 1, 3, 1}, {0, 1, 1, 1, 1, 2, 1, 3},
{1, 0, 2, -1, 2, 0, 3, -1}, {0, 1, 0, 2, 1, 2, 1, 3}, {1, -1, 1, 0, 2, -1, 3, -1},
}
var P = [][]int{
{0, 1, 1, 0, 1, 1, 2, 1}, {0, 1, 0, 2, 1, 0, 1, 1},
{1, 0, 1, 1, 2, 0, 2, 1}, {0, 1, 1, -1, 1, 0, 1, 1}, {0, 1, 1, 0, 1, 1, 1, 2},
{1, -1, 1, 0, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 1, 1, 2}, {0, 1, 1, 0, 1, 1, 2, 0},
}
var T = [][]int{
{0, 1, 0, 2, 1, 1, 2, 1}, {1, -2, 1, -1, 1, 0, 2, 0},
{1, 0, 2, -1, 2, 0, 2, 1}, {1, 0, 1, 1, 1, 2, 2, 0},
}
var U = [][]int{
{0, 1, 0, 2, 1, 0, 1, 2}, {0, 1, 1, 1, 2, 0, 2, 1},
{0, 2, 1, 0, 1, 1, 1, 2}, {0, 1, 1, 0, 2, 0, 2, 1},
}
var V = [][]int{
{1, 0, 2, 0, 2, 1, 2, 2}, {0, 1, 0, 2, 1, 0, 2, 0},
{1, 0, 2, -2, 2, -1, 2, 0}, {0, 1, 0, 2, 1, 2, 2, 2},
}
var W = [][]int{
{1, 0, 1, 1, 2, 1, 2, 2}, {1, -1, 1, 0, 2, -2, 2, -1},
{0, 1, 1, 1, 1, 2, 2, 2}, {0, 1, 1, -1, 1, 0, 2, -1},
}
var X = [][]int{{1, -1, 1, 0, 1, 1, 2, 0}}
var Y = [][]int{
{1, -2, 1, -1, 1, 0, 1, 1}, {1, -1, 1, 0, 2, 0, 3, 0},
{0, 1, 0, 2, 0, 3, 1, 1}, {1, 0, 2, 0, 2, 1, 3, 0}, {0, 1, 0, 2, 0, 3, 1, 2},
{1, 0, 1, 1, 2, 0, 3, 0}, {1, -1, 1, 0, 1, 1, 1, 2}, {1, 0, 2, -1, 2, 0, 3, 0},
}
var Z = [][]int{
{0, 1, 1, 0, 2, -1, 2, 0}, {1, 0, 1, 1, 1, 2, 2, 2},
{0, 1, 1, 1, 2, 1, 2, 2}, {1, -2, 1, -1, 1, 0, 2, -2},
}
var shapes = [][][]int{F, I, L, N, P, T, U, V, W, X, Y, Z}
var symbols = []byte("FILNPTUVWXYZ-")
const (
nRows = 8
nCols = 8
blank = 12
)
var grid [nRows][nCols]int
var placed [12]bool
func tryPlaceOrientation(o []int, r, c, shapeIndex int) bool {
for i := 0; i < len(o); i += 2 {
x := c + o[i+1]
y := r + o[i]
if x < 0 || x >= nCols || y < 0 || y >= nRows || grid[y][x] != -1 {
return false
}
}
grid[r][c] = shapeIndex
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = shapeIndex
}
return true
}
func removeOrientation(o []int, r, c int) {
grid[r][c] = -1
for i := 0; i < len(o); i += 2 {
grid[r+o[i]][c+o[i+1]] = -1
}
}
func solve(pos, numPlaced int) bool {
if numPlaced == len(shapes) {
return true
}
row := pos / nCols
col := pos % nCols
if grid[row][col] != -1 {
return solve(pos+1, numPlaced)
}
for i := range shapes {
if !placed[i] {
for _, orientation := range shapes[i] {
if !tryPlaceOrientation(orientation, row, col, i) {
continue
}
placed[i] = true
if solve(pos+1, numPlaced+1) {
return true
}
removeOrientation(orientation, row, col)
placed[i] = false
}
}
}
return false
}
func shuffleShapes() {
rand.Shuffle(len(shapes), func(i, j int) {
shapes[i], shapes[j] = shapes[j], shapes[i]
symbols[i], symbols[j] = symbols[j], symbols[i]
})
}
func printResult() {
for _, r := range grid {
for _, i := range r {
fmt.Printf("%c ", symbols[i])
}
fmt.Println()
}
}
func main() {
rand.Seed(time.Now().UnixNano())
shuffleShapes()
for r := 0; r < nRows; r++ {
for i := range grid[r] {
grid[r][i] = -1
}
}
for i := 0; i < 4; i++ {
var randRow, randCol int
for {
randRow = rand.Intn(nRows)
randCol = rand.Intn(nCols)
if grid[randRow][randCol] != blank {
break
}
}
grid[randRow][randCol] = blank
}
if solve(0, 0) {
printResult()
} else {
fmt.Println("No solution")
}
} | 454Pentomino tiling
| 0go
| s4xqa |
null | 449Percolation/Mean cluster density
| 11kotlin
| 87d0q |
import Control.Monad
import Control.Monad.Random
import Data.Array.Unboxed
import Data.List
import Formatting
data Field = Field { f :: UArray (Int, Int) Char
, hWall :: UArray (Int, Int) Bool
, vWall :: UArray (Int, Int) Bool
}
percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)])
percolateR [] (Field f h v) = (Field f h v, [])
percolateR seep (Field f h v) =
let ((xLo,yLo),(xHi,yHi)) = bounds f
validSeep = filter (\p@(x,y) -> x >= xLo
&& x <= xHi
&& y >= yLo
&& y <= yHi
&& f!p == ' ') $ nub $ sort seep
north (x,y) = if v ! (x ,y ) then [] else [(x ,y-1)]
south (x,y) = if v ! (x ,y+1) then [] else [(x ,y+1)]
west (x,y) = if h ! (x ,y ) then [] else [(x-1,y )]
east (x,y) = if h ! (x+1,y ) then [] else [(x+1,y )]
neighbors (x,y) = north(x,y) ++ south(x,y) ++ west(x,y) ++ east(x,y)
in percolateR
(concatMap neighbors validSeep)
(Field (f // map (\p -> (p,'.')) validSeep) h v)
percolate :: Field -> Field
percolate start@(Field f _ _) =
let ((_,_),(xHi,_)) = bounds f
(final, _) = percolateR [(x,0) | x <- [0..xHi]] start
in final
initField :: Int -> Int -> Double -> Rand StdGen Field
initField width height threshold = do
let f = listArray ((0,0), (width-1, height-1)) $ repeat ' '
hrnd <- fmap (<threshold) <$> getRandoms
let h0 = listArray ((0,0),(width, height-1)) hrnd
h1 = h0 // [((0,y), True) | y <- [0..height-1]]
h2 = h1 // [((width,y), True) | y <- [0..height-1]]
vrnd <- fmap (<threshold) <$> getRandoms
let v0 = listArray ((0,0),(width-1, height)) vrnd
v1 = v0 // [((x,0), True) | x <- [0..width-1]]
return $ Field f h2 v1
leaks :: Field -> [Bool]
leaks (Field f _ v) =
let ((xLo,_),(xHi,yHi)) = bounds f
in [f!(x,yHi)=='.' && not (v!(x,yHi+1)) | x <- [xLo..xHi]]
oneTest :: Int -> Int -> Double -> Rand StdGen Bool
oneTest width height threshold =
or.leaks.percolate <$> initField width height threshold
multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double
multiTest testCount width height threshold = do
results <- replicateM testCount $ oneTest width height threshold
let leakyCount = length $ filter id results
return $ fromIntegral leakyCount / fromIntegral testCount
alternate :: [a] -> [a] -> [a]
alternate [] _ = []
alternate (a:as) bs = a: alternate bs as
showField :: Field -> IO ()
showField field@(Field a h v) = do
let ((xLo,yLo),(xHi,yHi)) = bounds a
fLines = [ [ a!(x,y) | x <- [xLo..xHi]] | y <- [yLo..yHi]]
hLines = [ [ if h!(x,y) then '|' else ' ' | x <- [xLo..xHi+1]] | y <- [yLo..yHi]]
vLines = [ [ if v!(x,y) then '-' else ' ' | x <- [xLo..xHi]] | y <- [yLo..yHi+1]]
lattice = [ [ '+' | x <- [xLo..xHi+1]] | y <- [yLo..yHi+1]]
hDrawn = zipWith alternate hLines fLines
vDrawn = zipWith alternate lattice vLines
mapM_ putStrLn $ alternate vDrawn hDrawn
let leakLine = [ if l then '.' else ' ' | l <- leaks field]
putStrLn $ alternate (repeat ' ') leakLine
main :: IO ()
main = do
g <- getStdGen
let threshold = 0.45
(startField, g2) = runRand (initField 10 10 threshold) g
putStrLn ("Unpercolated field with " ++ show threshold ++ " threshold.")
putStrLn ""
showField startField
putStrLn ""
putStrLn "Same field after percolation."
putStrLn ""
showField $ percolate startField
let testCount = 10000
densityCount = 10
putStrLn ""
putStrLn ("Results of running percolation test " ++ show testCount ++ " times with thresholds ranging from 0/" ++ show densityCount ++ " to " ++ show densityCount ++ "/" ++ show densityCount ++ " .")
let densities = [0..densityCount]
let tests = sequence [multiTest testCount 10 10 v
| density <- densities,
let v = fromIntegral density / fromIntegral densityCount ]
let results = zip densities (evalRand tests g2)
mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) density densityCount x | (density,x) <- results] | 451Percolation/Bond percolation
| 8haskell
| 4fr5s |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.