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{...
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 r...
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 t...
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) ...
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[...
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) = (6...
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' --Keyw...
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, 2...
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).filt...
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; ...
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; ...
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', 'p...
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 "B...
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]]); ...
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=...
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 ....
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 := ne...
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_...
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.val...
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...
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_su...
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 m...
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,-2...
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:", pierpontP...
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 ? p...
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'); ...
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 = ...
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)...
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 pe...
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 s3i...
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] = tem...
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(re...
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 ...
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 (...
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 ...
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'); ...
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 ...
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<...
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 { ...
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)) ...
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) } } ...
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...
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 < 1...
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 ? '+...
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 ...
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(Syste...
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_ele...
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(pl...
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 _ => { ...
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) | tot...
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 <...
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; ...
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 = atomi...
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...
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.Fiel...
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...
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...
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() } } }"...
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 **dec...
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) $ [reve...
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...
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); ...
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 ...
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 = fi...
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] = $patter...
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 cell...
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(" ...
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 := fa...
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 { ...
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...
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;...
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); Sy...
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 ...
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...
451Percolation/Bond percolation
8haskell
4fr5s