code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
import Control.Monad.Random
import Control.Applicative
import Text.Printf
import Control.Monad
import Data.Bits
data OneRun = OutRun | InRun deriving (Eq, Show)
randomList :: Int -> Double -> Rand StdGen [Int]
randomList n p = take n . map f <$> getRandomRs (0,1)
where f n = if (n > p) then 0 else 1
countRuns xs =... | 447Percolation/Mean run density | 8haskell | c0494 |
null | 448Percolation/Site percolation | 11kotlin | fpydo |
(defn perfect-shuffle [deck]
(let [half (split-at (/ (count deck) 2) deck)]
(interleave (first half) (last half))))
(defn solve [deck-size]
(let [original (range deck-size)
trials (drop 1 (iterate perfect-shuffle original))
predicate #(= original %)]
(println (format "%5s:%s" deck-size
... | 452Perfect shuffle | 6clojure | sg0qr |
perfectTotients :: [Int]
perfectTotients =
filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate )) [2 ..]
:: Int -> Int
= memoize (\n -> length (filter ((1 ==) . gcd n) [1 .. n]))
memoize :: (Int -> a) -> (Int -> a)
memoize f = (!!) (f <$> [0 ..])
main :: IO ()
main = print $ take 20 perfectTotients | 450Perfect totient numbers | 8haskell | 0ris7 |
import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; | 436Pick random element | 9java | q4lxa |
var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)]; | 436Pick random element | 10javascript | ih4ol |
(function (p) {
return [
p.split('').reverse().join(''),
p.split(' ').map(function (x) {
return x.split('').reverse().join('');
}).join(' '),
p.split(' ').reverse().join(' ')
].join('\n');
})('rosetta code phrase reversal'); | 437Phrase reversals | 10javascript | dbgnu |
package main
import (
"fmt"
"math/big"
) | 444Permutations/Derangements | 0go | l8jcw |
package pentominotiling;
import java.util.*;
public class PentominoTiling {
static final char[] symbols = "FILNPTUVWXYZ-".toCharArray();
static final Random rand = new Random();
static final int nRows = 8;
static final int nCols = 8;
static final int blank = 12;
static int[][] grid = new in... | 454Pentomino tiling | 9java | tpdf9 |
$fill = 'x';
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub deq { defined $_[0] && $_[0] eq $_[1] }
sub perctest {
my($grid) = @_;
generate($grid);
my $block = 1;
for my $y (0..$grid-1) {
for my $x (0..$grid-1) {
fill($x, $y, $block++) if $perc[$y][$x] eq $fill
}
... | 449Percolation/Mean cluster density | 2perl | 4fj5d |
null | 451Percolation/Bond percolation | 11kotlin | 3eyz5 |
my $block = '';
my $water = '+';
my $pore = ' ';
my $grid = 15;
my @site;
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub deq { defined $_[0] && $_[0] eq $_[1] }
sub percolate {
my($prob) = shift || 0.6;
$site[0] = [($pore) x $grid];
for my $y (1..$grid) {
for my $x (0..$grid-1) {
... | 448Percolation/Site percolation | 2perl | hyajl |
null | 445Perlin noise | 9java | 87306 |
import java.util.ArrayList;
import java.util.List;
public class PerfectTotientNumbers {
public static void main(String[] args) {
computePhi();
int n = 20;
System.out.printf("The first%d perfect totient numbers:%n%s%n", n, perfectTotient(n));
}
private static final List<Integer> pe... | 450Perfect totient numbers | 9java | a2x1y |
import BigInt
import Foundation
public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) {
var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n))
primes.first[0] = 2
var count1 = 1, count2 = 0
var s = [BigInt(1)]
var i2 = 0, i3 = 0, k = 1
var n2 = Big... | 433Pierpont primes | 17swift | ojr8k |
def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def subfact
subfact = { BigInteger n -> (n == 0) ? 1: (n == 1) ? 0: ((n-1) * (subfact(n-1) + subfact(n-2))) }
def derangement = { List l ->
def d = []
if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d <... | 444Permutations/Derangements | 7groovy | 6w53o |
null | 442Permutations by swapping | 11kotlin | km8h3 |
from itertools import combinations as comb
def statistic(ab, a):
sumab, suma = sum(ab), sum(a)
return ( suma / len(a) -
(sumab -suma) / (len(ab) - len(a)) )
def permutationTest(a, b):
ab = a + b
Tobs = statistic(ab, a)
under = 0
for count, perm in enumerate(comb(ab, len(a)), 1):
... | 440Permutation test | 3python | yxj6q |
null | 454Pentomino tiling | 11kotlin | o708z |
my @bond;
my $grid = 10;
my $water = '';
$D{$_} = $i++ for qw<DeadEnd Up Right Down Left>;
sub percolate {
generate(shift || 0.6);
fill(my $x = 1,my $y = 0);
my @stack;
while () {
if (my $dir = direction($x,$y)) {
push @stack, [$x,$y];
($x,$y) = move($dir, $x, $y)
... | 451Percolation/Bond percolation | 2perl | pcab0 |
null | 445Perlin noise | 11kotlin | wunek |
(() => {
'use strict'; | 450Perfect totient numbers | 10javascript | sgoqz |
null | 436Pick random element | 11kotlin | 1l6pd |
import Control.Monad (forM_)
import Data.List (permutations)
derangements
:: Eq a
=> [a] -> [[a]]
derangements = (\x -> filter (and . zipWith (/=) x)) <*> permutations
subfactorial
:: (Eq a, Num a)
=> a -> a
subfactorial 0 = 1
subfactorial 1 = 0
subfactorial n = (n - 1) * (subfactorial (n - 1) + subfactori... | 444Permutations/Derangements | 8haskell | 1lops |
_JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
local loc=self.positions[i]+self.directi... | 442Permutations by swapping | 1lua | b9oka |
permutation.test <- function(treatment, control) {
perms <- combinations(length(treatment)+length(control),
length(treatment),
c(treatment, control),
set=FALSE)
p <- mean(rowMeans(perms) <= mean(treatment))
c(under=p, over=(1-p))
} | 440Permutation test | 13r | t14fz |
use strict;
use warnings;
my $size = shift // 8;
sub rotate
{
local $_ = shift;
my $ans = '';
$ans .= "\n" while s/.$/$ans .= $&; ''/gem;
$ans;
}
sub topattern
{
local $_ = shift;
s/.+/ $& . ' ' x ($size - length $&)/ge;
s/^\s+|\s+\z//g;
[ tr/ \nA-Z/.. /r, lc tr/ \n/\0/r, substr $_, 0, 1 ];
... | 454Pentomino tiling | 2perl | gf54e |
from __future__ import division
from random import random
import string
from math import fsum
n_range, p, t = (2**n2 for n2 in range(4, 14, 2)), 0.5, 5
N = M = 15
NOT_CLUSTERED = 1
cell2char = '
def newgrid(n, p):
return [[int(random() < p) for x in range(n)] for y in range(n)]
def pgrid(cell):
for n in... | 449Percolation/Mean cluster density | 3python | gth4h |
null | 447Percolation/Mean run density | 11kotlin | ih3o4 |
from random import random
import string
from pprint import pprint as pp
M, N, t = 15, 15, 100
cell2char = '
NOT_VISITED = 1
class PercolatedException(Exception): pass
def newgrid(p):
return [[int(random() < p) for m in range(M)] for n in range(N)]
def pgrid(cell, percolated=None):
for n in range(N):... | 448Percolation/Site percolation | 3python | kmehf |
local p = {
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 13... | 445Perlin noise | 1lua | x5dwz |
package cards
import (
"math/rand"
) | 438Playing cards | 0go | x5mwf |
package main
import "fmt"
func pernicious(w uint32) bool {
const (
ff = 1<<32 - 1
mask1 = ff / 3
mask3 = ff / 5
maskf = ff / 17
maskp = ff / 255
)
w -= w >> 1 & mask1
w = w&mask3 + w>>2&mask3
w = (w + w>>4) & maskf
return 0xa08a28ac>>(w*maskp>>24)&1 !... | 441Pernicious numbers | 0go | unavt |
null | 437Phrase reversals | 11kotlin | evya4 |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Derangement {
public static void main(String[] args) {
System.out.println("derangements for n = 4\n");
for (Object d : (ArrayList)(derangements(4, false)[0])) {
System.out.println(Arrays.toString(... | 444Permutations/Derangements | 9java | 73wrj |
from collections import namedtuple
from random import random
from pprint import pprint as pp
Grid = namedtuple('Grid', 'cell, hwall, vwall')
M, N, t = 10, 10, 100
class PercolatedException(Exception): pass
HVF = [(' .', ' _'), (':', '|'), (' ', '
def newgrid(p):
hwall = [[int(random() < p) for m in range(M)]
... | 451Percolation/Bond percolation | 3python | 1lepc |
null | 450Perfect totient numbers | 11kotlin | hypj3 |
import groovy.transform.TupleConstructor
enum Pip {
ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING
}
enum Suit {
DIAMONDS, SPADES, HEARTS, CLUBS
}
@TupleConstructor
class Card {
final Pip pip
final Suit suit
String toString() { "$pip of $suit" }
}
class Deck {
p... | 438Playing cards | 7groovy | pctbo |
class example{
static void main(String[] args){
def n=0;
def counter=0;
while(counter<25){
if(print(n)){
counter++;}
n=n+1;
}
println();
def x=888888877;
while(x<888888889){
print(x);
x++;}
}
static def print(def a){
def primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47];
def c=Integer.toBinaryString(a);
String d=c;
def... | 441Pernicious numbers | 7groovy | 9shm4 |
null | 437Phrase reversals | 1lua | wumea |
package main
import (
"fmt"
"image/jpeg"
"os"
"log"
"image"
)
func loadJpeg(filename string) (image.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
img, err := jpeg.Decode(f)
if err != nil {
return nil, err
... | 453Percentage difference between images | 0go | gtg4n |
import System.Random
data Pip = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten |
Jack | Queen | King | Ace
deriving (Ord, Enum, Bounded, Eq, Show)
data Suit = Diamonds | Spades | Hearts | Clubs
deriving (Ord, Enum, Bounded, Eq, Show)
type Card = (Pip, Suit)
fullRange :: (Bounded a, En... | 438Playing cards | 8haskell | yxk66 |
module Pernicious
where
isPernicious :: Integer -> Bool
isPernicious num = isPrime $ toInteger $ length $ filter ( == 1 ) $ toBinary num
isPrime :: Integer -> Bool
isPrime number = divisors number == [1, number]
where
divisors :: Integer -> [Integer]
divisors number = [ m | m <- [1 .. number] , numb... | 441Pernicious numbers | 8haskell | wuzed |
math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)]) | 436Pick random element | 1lua | a2y1v |
use strict;
use warnings;
sub perms(&@) {
my $callback = shift;
my @perm = map [$_, -1], @_;
$perm[0][1] = 0;
my $sign = 1;
while( ) {
$callback->($sign, map $_->[0], @perm);
$sign *= -1;
my ($chosen, $index) = (-1, -1);
for my $i ( 0 .. $
($chosen, $index) ... | 442Permutations by swapping | 2perl | 3e4zs |
def statistic(ab, a)
sumab, suma = ab.inject(:+).to_f, a.inject(:+).to_f
suma / a.size - (sumab - suma) / (ab.size - a.size)
end
def permutationTest(a, b)
ab = a + b
tobs = statistic(ab, a)
under = count = 0
ab.combination(a.size) do |perm|
under += 1 if statistic(ab, perm) <= tobs
count += 1
end... | 440Permutation test | 14ruby | 9skmz |
import Bitmap
import Bitmap.Netpbm
import Bitmap.RGB
import Control.Monad
import Control.Monad.ST
import System.Environment (getArgs)
main = do
[path1, path2] <- getArgs
image1 <- readNetpbm path1
image2 <- readNetpbm path2
diff <- stToIO $ imageDiff image1 image2
putStrLn $ "Difference: " ++ show... | 453Percentage difference between images | 8haskell | sgsqk |
from itertools import product
minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)), ((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
((131843... | 454Pentomino tiling | 3python | rt4gq |
let randMax = 32767.0
let filled = 1
let rightWall = 2
let bottomWall = 4
final class Percolate {
let height: Int
let width: Int
private var grid: [Int]
private var end: Int
init(height: Int, width: Int) {
self.height = height
self.width = width
self.end = width
self.grid = [Int](repeating... | 451Percolation/Bond percolation | 17swift | a2w1i |
sub R {
my ($n, $p) = @_;
my $r = join '',
map { rand() < $p ? 1 : 0 } 1 .. $n;
0+ $r =~ s/1+//g;
}
use constant t => 100;
printf "t=%d\n", t;
for my $p (qw(.1 .3 .5 .7 .9)) {
printf "p=%f, K(p)=%f\n", $p, $p*(1-$p);
for my $n (qw(10 100 1000)) {
my $r; $r += R($n, $p) for 1 .. t; $r... | 447Percolation/Mean run density | 2perl | rzpgd |
package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(... | 443Pi | 0go | 9s7mt |
use strict;
use warnings;
my @players = @ARGV;
@players = qw(Joe Mike);
my @scores = (0) x @players;
while( 1 ) {
PLAYER: for my $i ( 0 .. $
my $name = $players[$i];
my $score = $scores[$i];
my $roundscore = 1 + int rand 6;
print "$name, your score so far is $score.\n";
print "You rolled a $roundscore.\n";
... | 434Pig the dice game | 2perl | un8vr |
null | 444Permutations/Derangements | 11kotlin | unbvc |
fn main() {
let treatment = vec![85, 88, 75, 66, 25, 29, 83, 39, 97];
let control = vec![68, 41, 10, 49, 16, 65, 32, 92, 28, 98];
let mut data_set = control.clone();
data_set.extend_from_slice(&treatment);
let greater = combinations(treatment.iter().sum(), treatment.len() as i64, &data_set) as f64... | 440Permutation test | 15rust | c0b9z |
object PermutationTest extends App {
private val data =
Array(85, 88, 75, 66, 25, 29, 83, 39, 97, 68, 41, 10, 49, 16, 65, 32, 92, 28, 98)
private var (total, treat) = (1.0, 0)
private def pick(at: Int, remain: Int, accu: Int, treat: Int): Int = {
if (remain == 0) return if (accu > treat) 1 else 0
pi... | 440Permutation test | 16scala | via2s |
package main
import "fmt"
type Deck struct {
Cards []int
length int
}
func NewDeck(deckSize int) (res *Deck){
if deckSize % 2 != 0{
panic("Deck size must be even")
}
res = new(Deck)
res.Cards = make([]int, deckSize)
res.length = deckSize
for i,_ := range res.Cards{
res.Cards[i] = i
}
return
}
func (d ... | 452Perfect shuffle | 0go | mq9yi |
use strict;
use warnings;
use experimental 'signatures';
use constant permutation => qw{
151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69
142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252
219 203 117 35 11 32 57 177 33 88 237 149 56 87 174... | 445Perlin noise | 2perl | l87c5 |
use ntheory qw(euler_phi);
sub phi_iter {
my($p) = @_;
euler_phi($p) + ($p == 2 ? 0 : phi_iter(euler_phi($p)));
}
my @perfect;
for (my $p = 2; @perfect < 20 ; ++$p) {
push @perfect, $p if $p == phi_iter($p);
}
printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect; | 450Perfect totient numbers | 2perl | zaytb |
BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
String nn
boolean first = true
while (true) {
(nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \
? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \
: ['' , first, q*k , (2*q + r... | 443Pi | 7groovy | zaut5 |
public class Pernicious{ | 441Pernicious numbers | 9java | kmohm |
null | 444Permutations/Derangements | 1lua | 5dpu6 |
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public enum ImgDiffPercent {
;
public static void main(String[] args) throws IOException { | 453Percentage difference between images | 9java | 1l1p2 |
from __future__ import division
from random import random
from math import fsum
n, p, t = 100, 0.5, 500
def newv(n, p):
return [int(random() < p) for i in range(n)]
def runs(v):
return sum((a & ~b) for a, b in zip(v, v[1:] + [0]))
def mean_run_density(n, p):
return runs(newv(n, p)) / n
for p10 in ran... | 447Percolation/Mean run density | 3python | 731rm |
shuffle :: [a] -> [a]
shuffle lst = let (a,b) = splitAt (length lst `div` 2) lst
in foldMap (\(x,y) -> [x,y]) $ zip a b
findCycle :: Eq a => (a -> a) -> a -> [a]
findCycle f x = takeWhile (/= x) $ iterate f (f x)
main = mapM_ report [ 8, 24, 52, 100, 1020, 1024, 10000 ]
where
report n = putStrL... | 452Perfect shuffle | 8haskell | kmbh0 |
pi_ = g (1, 0, 1, 1, 3, 3)
where
g (q, r, t, k, n, l) =
if 4 * q + r - t < n * t
then n:
g
( 10 * q
, 10 * (r - n * t)
, t
, k
, div (10 * (3 * q + r)) t - 10 * n
, l)
else g
... | 443Pi | 8haskell | b98k2 |
error_reporting(E_ALL & ~ ( E_NOTICE | E_WARNING ));
define('MAXSCORE', 100);
define('PLAYERCOUNT', 2);
$confirm = array('Y', 'y', '');
while (true) {
printf(' Player%d: (%d,%d) Rolling? (Yn) ', $player,
$safeScore[$player], $score);
if ($safeScore[$player] + $score < MAXSCORE &&
in_a... | 434Pig the dice game | 12php | 8740m |
use feature 'say';
my $s = "rosetta code phrase reversal";
say "0. Input : ", $s;
say "1. String reversed : ", scalar reverse $s;
say "2. Each word reversed : ", join " ", reverse split / /, reverse $s;
say "3. Word-order reversed: ", join " ", reverse split / /,$s;
say "2. Each word reversed : ", $s... | 437Phrase reversals | 2perl | c0a9a |
from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) if pp... | 442Permutations by swapping | 3python | 6wg3w |
function getImageData(url, callback) {
var img = document.createElement('img');
var canvas = document.createElement('canvas');
img.onload = function () {
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
callback(ctx.getImageData(0, 0, img.w... | 453Percentage difference between images | 10javascript | q4qx8 |
import java.util.Arrays;
import java.util.stream.IntStream;
public class PerfectShuffle {
public static void main(String[] args) {
int[] sizes = {8, 24, 52, 100, 1020, 1024, 10_000};
for (int size : sizes)
System.out.printf("%5d:%5d%n", size, perfectShuffle(size));
}
static in... | 452Perfect shuffle | 9java | 4fg58 |
public enum Pip { Two, Three, Four, Five, Six, Seven,
Eight, Nine, Ten, Jack, Queen, King, Ace } | 438Playing cards | 9java | db4n9 |
'''
See: http:
This program scores and throws the dice for a two player game of Pig
'''
from random import randint
playercount = 2
maxscore = 100
safescore = [0] * playercount
player = 0
score=0
while max(safescore) < maxscore:
rolling = input(
% (player, safescore[player], score)).strip().l... | 434Pig the dice game | 3python | 5doux |
null | 441Pernicious numbers | 11kotlin | gtx4d |
null | 453Percentage difference between images | 11kotlin | j6j7r |
int perfect(int n) {
int max = (int)sqrt((double)n) + 1;
int tot = 1;
int i;
for (i = 2; i < max; i++)
if ( (n % i) == 0 ) {
tot += i;
int q = n / i;
if (q > i)
tot += q;
}
return tot == n;
}
int main() {
int n;
for (n = ... | 455Perfect numbers | 5c | 9q6m1 |
(() => {
'use strict'; | 452Perfect shuffle | 10javascript | hykjh |
def perlin_noise(x, y, z):
X = int(x) & 255
Y = int(y) & 255
Z = int(z) & 255
x -= int(x)
y -= int(y)
z -= int(z)
u = fade(x)
v = fade(y) ... | 445Perlin noise | 3python | 2ojlz |
from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def (n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = (n)
parts +... | 450Perfect totient numbers | 3python | 3emzc |
function Card(pip, suit) {
this.pip = pip;
this.suit = suit;
this.toString = function () {
return this.pip + ' ' + this.suit;
};
}
function Deck() {
var pips = '2 3 4 5 6 7 8 9 10 Jack Queen King Ace'.split(' ');
var suits = 'Clubs Hearts Spades Diamonds'.split(' ');
this.deck = [... | 438Playing cards | 10javascript | 6wh38 |
<?php
$strin = ;
echo .$strin.;
echo .strrev($strin).;
$str_words_reversed = ;
$temp = explode(, $strin);
foreach($temp as $word)
$str_words_reversed .= strrev($word).;
echo .$str_words_reversed.;
$str_word_order_reversed = ;
$temp = explode(, $strin);
for($i=(count($temp)-1); $i>=0; $i--)
$str_word_order... | 437Phrase reversals | 12php | x59w5 |
Bitmap.loadPPM = function(self, filename)
local fp = io.open( filename, "rb" )
if fp == nil then return false end
local head, width, height, depth, tail = fp:read("*line", "*number", "*number", "*number", "*line")
self.width, self.height = width, height
self:alloc()
self:clear( {0,0,0} )
for y = 1, se... | 453Percentage difference between images | 1lua | hyhj8 |
import java.math.BigInteger ;
public class Pi {
final BigInteger TWO = BigInteger.valueOf(2) ;
final BigInteger THREE = BigInteger.valueOf(3) ;
final BigInteger FOUR = BigInteger.valueOf(4) ;
final BigInteger SEVEN = BigInteger.valueOf(7) ;
BigInteger q = BigInteger.ONE ;
BigInteger r = BigInteger.ZERO ;
... | 443Pi | 9java | gte4m |
null | 441Pernicious numbers | 1lua | rzqga |
sub d {
$
grep { $_[$_] != @{$_[0]} } 1 .. $
: $_[0]
}
sub deranged {
my ($result, @avail) = @_;
return $result if !@avail;
my @list;
for my $i (0 .. $
next if $... | 444Permutations/Derangements | 2perl | 8760w |
def perms(n)
p = Array.new(n+1){|i| -i}
s = 1
loop do
yield p[1..-1].map(&:abs), s
k = 0
for i in 2..n
k = i if p[i] < 0 and p[i].abs > p[i-1].abs and p[i].abs > p[k].abs
end
for i in 1...n
k = i if p[i] > 0 and p[i].abs > p[i+1].abs and p[i].abs > p[k].abs
end
break if k.... | 442Permutations by swapping | 14ruby | mq7yj |
int main (int argc, char *argv[]) {
if (argc < 2) {
printf();
return 0;
}
int x;
for (x = 0; argv[1][x] != '\0'; x++);
int f, v, m;
for(f=0; f < x; f++) {
for(v = x-1; v > f; v-- ) {
if (argv[1][v-1] > argv[1][v]) {
m=argv[1][v-1];
argv[1][v-1]=argv[1][v];
argv[1]... | 456Permutations | 5c | mxzys |
null | 452Perfect shuffle | 11kotlin | l82cp |
let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
let u = 3n*(3n*i+1n)*(3n*i+2n);
r = 10n*u*(q*(5n*i-2n)+r-y*t);
q = 10n*q*i*(2n*i-1n);
t = t*u;
i = i+1n;
process.stdout.write(y.toString());
if (i === 3n) { process.stdout.write('.'); }
} | 443Pi | 10javascript | km0hq |
null | 442Permutations by swapping | 15rust | 9sjmm |
object JohnsonTrotter extends App {
private def perm(n: Int): Unit = {
val p = new Array[Int](n) | 442Permutations by swapping | 16scala | 2oblb |
(defn proper-divisors [n]
(if (< n 4)
[1]
(->> (range 2 (inc (quot n 2)))
(filter #(zero? (rem n %)))
(cons 1))))
(defn perfect? [n]
(= (reduce + (proper-divisors n)) n)) | 455Perfect numbers | 6clojure | uilvi |
null | 452Perfect shuffle | 1lua | 2ovl3 |
require
class Integer
def
prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
end
def perfect_totient?
f, sum = self, 0
until f == 1 do
f = f.
sum += f
end
self == sum
end
end
puts (1..).lazy.select(&:perfect_totient?).first(20).join() | 450Perfect totient numbers | 14ruby | yxc6n |
const val FACES = "23456789TJQKA"
const val SUITS = "shdc"
fun createDeck(): List<String> {
val cards = mutableListOf<String>()
FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } }
return cards
}
fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n)
fun dealBottomDeck(deck: Li... | 438Playing cards | 11kotlin | 0rlsf |
my @array = qw(a b c);
print $array[ rand @array ]; | 436Pick random element | 2perl | mq1yz |
fn main() {
println!("{}", noise(3.14, 42.0, 7.0));
}
fn noise(x: f64, y: f64, z: f64) -> f64 {
let x0 = x.floor() as usize & 255;
let y0 = y.floor() as usize & 255;
let z0 = z.floor() as usize & 255;
let x = x - x.floor();
let y = y - y.floor();
let z = z - z.floor();
let u = fade(x);
let v = fade(y);
let... | 445Perlin noise | 15rust | 5dbuq |
null | 450Perfect totient numbers | 16scala | l8ucq |
class PigGame
Player = Struct.new(:name, :safescore, :score) do
def bust!() self.score = safescore end
def stay!() self.safescore = score end
def to_s() end
end
def initialize(names, maxscore=100, die_sides=6)
rotation = names.map {|name| Player.new(name,0,0) }
rotation.cycle do |player|
... | 434Pig the dice game | 14ruby | gtn4q |
$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)]; | 436Pick random element | 12php | evma9 |
>>> phrase =
>>> phrase[::-1]
'lasrever esarhp edoc attesor'
>>> ' '.join(word[::-1] for word in phrase.split())
'attesor edoc esarhp lasrever'
>>> ' '.join(phrase.split()[::-1])
'reversal phrase code rosetta'
>>> | 437Phrase reversals | 3python | l8ecv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.