code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
(ns penney.core
(:gen-class))
(def heads \H)
(def tails \T)
(defn flip-coin []
(let [flip (rand-int 2)]
(if (= flip 0) heads tails)))
(defn turn [coin]
(if (= coin heads) tails heads))
(defn first-index [combo coll]
(some #(if (= (second %) combo) (first %)) coll))
(defn find-winner [h c]
(if (< h c)... | 460Penney's game | 6clojure | csf9b |
package main
import "github.com/fogleman/gg"
var points []gg.Point
const width = 81
func peano(x, y, lg, i1, i2 int) {
if lg == 1 {
px := float64(width-x) * 10
py := float64(width-y) * 10
points = append(points, gg.Point{px, py})
return
}
lg /= 3
peano(x+2*i1*lg, y+2*... | 459Peano curve | 0go | 283l7 |
import java.io.*;
public class PeanoCurve {
public static void main(final String[] args) {
try (Writer writer = new BufferedWriter(new FileWriter("peano_curve.svg"))) {
PeanoCurve s = new PeanoCurve(writer);
final int length = 8;
s.currentAngle = 90;
s.curren... | 459Peano curve | 9java | j3v7c |
sub solve_pell {
my ($n) = @_;
use bigint try => 'GMP';
my $x = int(sqrt($n));
my $y = $x;
my $z = 1;
my $r = 2 * $x;
my ($e1, $e2) = (1, 0);
my ($f1, $f2) = (0, 1);
for (; ;) {
$y = $r * $z - $y;
$z = int(($n - $y * $y) / $z);
$r = int(($x + $y) / $z);
... | 458Pell's equation | 2perl | 7zvrh |
enum Piece {
Empty,
Black,
White,
};
typedef struct Position_t {
int x, y;
} Position;
struct Node_t {
Position pos;
struct Node_t *next;
};
void releaseNode(struct Node_t *head) {
if (head == NULL) return;
releaseNode(head->next);
head->next = NULL;
free(head);
}
typedef... | 462Peaceful chess queen armies | 5c | 8rb04 |
next.perm <- function(a) {
n <- length(a)
i <- n
while (i > 1 && a[i - 1] >= a[i]) i <- i - 1
if (i == 1) {
NULL
} else {
j <- i
k <- n
while (j < k) {
s <- a[j]
a[j] <- a[k]
a[k] <- s
j <- j + 1
k <- k - 1
}
s <- a[i - 1]
j <- i
while (a[j] <= s) ... | 456Permutations | 13r | 9q3mg |
local PeanoLSystem = {
axiom = "L",
rules = {
L = "LFRFL-F-RFLFR+F+LFRFL",
R = "RFLFR+F+LFRFL-F-RFLFR"
},
eval = function(self, n)
local source, result = self.axiom
for i = 1, n do
result = ""
for j = 1, #source do
local ch = source:sub(j,j)
result = result .. (self.r... | 459Peano curve | 1lua | 4d95c |
char* symbols[] = {, , ,
int length = DEFAULT_LENGTH;
int count = DEFAULT_COUNT;
unsigned seed;
char exSymbols = 0;
void GetPassword () {
int lengths[4] = {1, 1, 1, 1};
int count = 4;
while (count < length) {
lengths[rand()%4]++;
count++;
}
char password[length + 1];
... | 463Password generator | 5c | s4jq5 |
import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y)
r = (x + y)
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a ... | 458Pell's equation | 3python | j3u7p |
use strict;
use warnings;
use Tk;
my $size = 900;
my @particles;
my $maxparticles = 500;
my @colors = qw( red green blue yellow cyan magenta orange white );
my $mw = MainWindow->new;
my $c = $mw->Canvas( -width => $size, -height => $size, -bg => 'black',
)->pack;
$mw->Button(-text => 'Exit', -command => sub {$mw->... | 464Particle fountain | 2perl | fbad7 |
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my %rules = (
L => 'LFRFL-F-RFLFR+F+LFRFL',
R => 'RFLFR+F+LFRFL-F-RFLFR'
);
my $peano = 'L';
$peano =~ s/([LR])/$rules{$1}/eg for 1..4;
($x, $y) = (0, 0);
$theta = pi/2;
$r = 4;
for (split //, $peano) {
if (/F/) {
... | 459Peano curve | 2perl | o7e8x |
package main
import "fmt"
import "math/rand"
func main(){
var a1,a2,a3,y,match,j,k int
var inp string
y=1
for y==1{
fmt.Println("Enter your sequence:")
fmt.Scanln(&inp)
var Ai [3] int
var user [3] int
for j=0;j<3;j++{
if(inp[j]==104){
user[j]=1
}else{
user[j]=0
}
}
for k=0;k<3;k++{
Ai[k]=rand.Intn(2)
}
for user[0]==Ai[... | 460Penney's game | 0go | bm5kh |
mpz_t* partition(uint64_t n) {
mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
mpz_init_set_ui(pn[0], 1);
mpz_init_set_ui(pn[1], 1);
for (uint64_t i = 2; i < n + 2; i ++) {
mpz_init(pn[i]);
for (uint64_t k = 1, penta; ; k++) {
penta = k * (3 * k - 1) >> 1;
if (penta >= i) break;
if (k & 1) mpz_ad... | 465Partition function P | 5c | 1c2pj |
import qualified Data.List as L
import System.IO
import System.Random
data CoinToss = H | T deriving (Read, Show, Eq)
parseToss :: String -> [CoinToss]
parseToss [] = []
parseToss (s:sx)
| s == 'h' || s == 'H' = H: parseToss sx
| s == 't' || s == 'T' = T: parseToss sx
| otherwise = parseToss sx
notToss :: Coin... | 460Penney's game | 8haskell | dkxn4 |
package main
import (
"fmt"
"math/big"
)
func main() {
sequence()
bank()
rump()
}
func sequence() { | 461Pathological floating point problems | 0go | nhei1 |
void pascal(int a, int b, int mid, int top, int* x, int* y, int* z)
{
double ytemp = (top - 4 * (a + b)) / 7.;
if(fmod(ytemp, 1.) >= 0.0001)
{
x = 0;
return;
}
*y = ytemp;
*x = mid - 2 * a - *y;
*z = *y - *x;
}
int main()
{
int a = 11, b = 4, mid = 40, top = 151;
i... | 466Pascal's triangle/Puzzle | 5c | tp1f4 |
def solve_pell(n)
x = Integer.sqrt(n)
y = x
z = 1
r = 2*x
e1, e2 = 1, 0
f1, f2 = 0, 1
loop do
y = r*z - y
z = (n - y*y) / z
r = (x + y) / z
e1, e2 = e2, r*e2 + e1
f1, f2 = f2, r*f2 + f1
a, b = e2 + x*f2, f2
break a, b if a*a - n*b*b == 1
end
end
[61, 109, 181, 277].each {... | 458Pell's equation | 14ruby | ky4hg |
typedef struct bit_array_tag {
uint32_t size;
uint32_t* array;
} bit_array;
bool bit_array_create(bit_array* b, uint32_t size) {
uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
if (array == NULL)
return false;
b->size = size;
b->array = array;
return true;
}
void bit_ar... | 467Partition an integer x into n primes | 5c | 288lo |
package main
import "fmt"
const (
empty = iota
black
white
)
const (
bqueen = 'B'
wqueen = 'W'
bbullet = ''
wbullet = ''
)
type position struct{ i, j int }
func iabs(i int) int {
if i < 0 {
return -i
}
return i
}
func place(m, n int, pBlackQueens, pWhiteQueens *[]... | 462Peaceful chess queen armies | 0go | 5n3ul |
(ns pwdgen.core
(:require [clojure.set:refer [difference]]
[clojure.tools.cli:refer [parse-opts]])
(:gen-class))
(def minimum-length 4)
(def cli-options
[["-c" "--count NUMBER" "Number of passwords to generate"
:default 1
:parse-fn #(Integer/parseInt %)]
["-l" "--length NUMBER" "Length of th... | 463Password generator | 6clojure | nh1ik |
import java.util.*;
public class PenneysGame {
public static void main(String[] args) {
Random rand = new Random();
String compChoice = "", playerChoice;
if (rand.nextBoolean()) {
for (int i = 0; i < 3; i++)
compChoice += "HT".charAt(rand.nextInt(2));
... | 460Penney's game | 9java | s4bq0 |
use num_bigint::{ToBigInt, BigInt};
use num_traits::{Zero, One}; | 458Pell's equation | 15rust | bmgkx |
def pellFermat(n: Int): (BigInt,BigInt) = {
import scala.math.{sqrt, floor}
val x = BigInt(floor(sqrt(n)).toInt)
var i = 0 | 458Pell's equation | 16scala | alj1n |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Peaceful {
enum Piece {
Empty,
Black,
White,
}
public static class Position {
public int x, y;
public Position(int x, int y) {
this.x = x;
this.y = y;
... | 462Peaceful chess queen armies | 9java | bmvk3 |
import turtle as tt
import inspect
stack = []
def peano(iterations=1):
global stack
ivan = tt.Turtle(shape = , visible = True)
screen = tt.Screen()
screen.title()
screen.bgcolor()
screen.delay(0)
screen.setup(width=0.95, height=0.9)
walk = 1
def screenlength(k)... | 459Peano curve | 3python | ijwof |
null | 460Penney's game | 11kotlin | alr13 |
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FPProblems {
public static void wrongConvergence() {
int[] INDEXES = new int[] { 3, 4, 5, 6, 7, 8, 20, 30, 50, 100 }; | 461Pathological floating point problems | 9java | mxiym |
(def bottom [ [0 1 0], [11 0 0], [0 1 1], [4 0 0], [0 0 1] ])
(defn plus [v1 v2] (vec (map + v1 v2)))
(defn minus [v1 v2] (vec (map - v1 v2)))
(defn scale [n v] (vec (map #(* n %) v )))
(defn above [row] (map #(apply plus %) (partition 2 1 row)))
(def rows (reverse (take 5 (iterate above bottom)))) | 466Pascal's triangle/Puzzle | 6clojure | mxqyq |
p [1,2,3].permutation.to_a | 456Permutations | 14ruby | 5nluj |
install.packages("BiocManager")
BiocManager::install("HilbertCurve")
library(HilbertCurve)
library(circlize)
set.seed(123)
for(i in 1:512) {
peano = HilbertCurve(1, 512, level = 4, reference = TRUE, arrow = FALSE)
hc_points(peano, x1 = i, np = NULL, pch = 16, size = unit(3, "mm"))
} | 459Peano curve | 13r | s4pqy |
function penny_game()
local player, computer = "", ""
function player_choose()
io.write( "Enter your sequence of three H and/or T: " )
local t = io.read():upper()
if #t > 3 then t = t:sub( 1, 3 )
elseif #t < 3 then return ""
end
for i = 1, 3 do
c = t:... | 460Penney's game | 1lua | e27ac |
func solvePell<T: BinaryInteger>(n: T, _ a: inout T, _ b: inout T) {
func swap(_ a: inout T, _ b: inout T, mul by: T) {
(a, b) = (b, b * by + a)
}
let x = T(Double(n).squareRoot())
var y = x
var z = T(1)
var r = x << 1
var e1 = T(1)
var e2 = T(0)
var f1 = T(0)
var f2 = T(1)
while true {
... | 458Pell's equation | 17swift | h65j0 |
import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 until... | 462Peaceful chess queen armies | 11kotlin | rtmgo |
package main
import (
"fmt"
"math/big"
"time"
)
var p []*big.Int
var pd []int
func partDiffDiff(n int) int {
if n&1 == 1 {
return (n + 1) / 2
}
return n + 1
}
func partDiff(n int) int {
if n < 2 {
return 1
}
pd[n] = pd[n-1] + partDiffDiff(n-1)
return pd[n]
}
... | 465Partition function P | 0go | ywq64 |
pub fn permutations(size: usize) -> Permutations {
Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 }
}
pub struct Permutations {
idxs: Vec<usize>,
swaps: Vec<usize>,
i: usize,
}
impl Iterator for Permutations {
type Item = Vec<usize>;
fn next(&mut self) -> Option<Self::It... | 456Permutations | 15rust | 4d25u |
load_library :grammar
class Peano
include Processing::Proxy
attr_reader :draw_length, :vec, :theta, :axiom, :grammar
DELTA = 60
def initialize(vec)
@axiom = 'XF'
rules = {
'X' => 'X+YF++YF-FX--FXFX-YF+',
'Y' => '-FX+YFYF++YF+FX--FX-Y'
}
@grammar = Grammar.new(axiom, rules)
@... | 459Peano curve | 14ruby | dkqns |
null | 461Pathological floating point problems | 11kotlin | tpqf0 |
import java.math.BigInteger;
public class PartitionFunction {
public static void main(String[] args) {
long start = System.currentTimeMillis();
BigInteger result = partitions(6666);
long end = System.currentTimeMillis();
System.out.println("P(6666) = " + result);
System.out.... | 465Partition function P | 9java | 5nfuf |
null | 459Peano curve | 15rust | fbsd6 |
use 5.020;
use strict;
use warnings;
binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst());
sub binaryRand
{
return int(rand(2));
}
sub convert
{
my $randNum = binaryRand();
if($randNum == 0)
{
return "T"
}
else
{
return "H";
}
}
sub uSeq
{
print("P... | 460Penney's game | 2perl | 9qdmn |
package main
import (
"fmt"
"log"
)
var (
primes = sieve(100000)
foundCombo = false
)
func sieve(limit uint) []uint {
primes := []uint{2}
c := make([]bool, limit+1) | 467Partition an integer x into n primes | 0go | q55xz |
function p(n){
var a = new Array(n+1)
a[0] = 1n
for (let i = 1; i <= n; i++){
a[i] = 0n
for (let k = 1, s = 1; s <= i;){
a[i] += (k & 1 ? a[i-s]:-a[i-s])
k > 0 ? (s += k, k = -k):(k = -k+1, s = k*(3*k-1)/2)
}
}
return a[n]
}
var t = Date.now()
conso... | 465Partition function P | 10javascript | j3y7n |
package main
import "fmt" | 466Pascal's triangle/Puzzle | 0go | h6yjq |
use strict;
use warnings;
my $m = shift // 4;
my $n = shift // 5;
my %seen;
my $gaps = join '|', qr/-*/, map qr/.{$_}(?:-.{$_})*/s, $n-1, $n, $n+1;
my $attack = qr/(\w)(?:$gaps)(?!\1)\w/;
place( scalar ('-' x $n . "\n") x $n );
print "No solution to $m $n\n";
sub place
{
local $_ = shift;
$seen{$_}++ || /$atta... | 462Peaceful chess queen armies | 2perl | dkenw |
List(1, 2, 3).permutations.foreach(println) | 456Permutations | 16scala | 7z5r9 |
typedef int (*intfunc)(int);
typedef void (*pfunc)(int*, int);
pfunc partial(intfunc fin)
{
pfunc f;
static int idx = 0;
char cc[256], lib[256];
FILE *fp;
sprintf(lib, , ++idx);
sprintf(cc, , lib);
fp = popen(cc, );
fprintf(fp,
, fin);
fclose(fp);
*(void **)(&f) = dlsym(dlopen(lib, RTLD_LAZY), );
unlin... | 468Partial function application | 5c | p9mby |
import Data.List (delete, intercalate)
import Data.Numbers.Primes (primes)
import Data.Bool (bool)
partitions :: Int -> Int -> [Int]
partitions x n
| n <= 1 =
[ x
| x == last ps ]
| otherwise = go ps x n
where
ps = takeWhile (<= x) primes
go ps_ x 1 =
[ x
| x `elem` ps_ ]
go ps_ ... | 467Partition an integer x into n primes | 8haskell | mxxyf |
data Memo a = Node a (Memo a) (Memo a)
deriving Functor
memo :: Integral a => Memo p -> a -> p
memo (Node a l r) n
| n == 0 = a
| odd n = memo l (n `div` 2)
| otherwise = memo r (n `div` 2 - 1)
nats :: Memo Int
nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats)
partitions :: Memo Integer
partitions ... | 465Partition function P | 8haskell | h6mju |
puzzle = [["151"],["",""],["40","",""],["","","",""],["X","11","Y","4","Z"]] | 466Pascal's triangle/Puzzle | 8haskell | ijhor |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalsTrianglePuzzle {
public static void main(String[] args) {
Matrix mat = new Matrix(Arrays.asList(1d, 0d, 0d, 0d, 0d, 0d, 0d, 0d, -1d, 0d, 0d),
Arrays.asList(0d, 1d, 0d, 0d, 0d, 0... | 466Pascal's triangle/Puzzle | 9java | xu5wy |
from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in combinations(board, m)}
for blacks in placements:
bl... | 462Peaceful chess queen armies | 3python | fbwde |
from __future__ import print_function
import random
from time import sleep
first = random.choice([True, False])
you = ''
if first:
me = ''.join(random.sample('HT'*3, 3))
print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
while len(you) != 3 or any(ch not in 'HT' for c... | 460Penney's game | 3python | csf9q |
use bigrat;
@s = qw(2, -4);
for my $n (2..99) {
$s[$n]= 111.0 - 1130.0/$s[-1] + 3000.0/($s[-1]*$s[-2]);
}
for $n (3..8, 20, 30, 35, 50, 100) {
($nu,$de) = $s[$n-1] =~ m
printf "n =%3d%18.15f\n", $n, $nu/$de;
} | 461Pathological floating point problems | 2perl | kyvhc |
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal;
}
static unsigned int _parseHex ( con... | 469Parse an IP Address | 5c | wvlec |
typedef struct node_
struct node_
\
node_
node_
node->value = v; \
node->left = node->right = 0; ... | 470Parametric polymorphism | 5c | csw9c |
import java.util.Arrays;
import java.util.stream.IntStream;
public class PartitionInteger {
private static final int[] primes = IntStream.concat(IntStream.of(2), IntStream.iterate(3, n -> n + 2))
.filter(PartitionInteger::isPrime)
.limit(50_000)
.toArray();
private static boolean isPri... | 467Partition an integer x into n primes | 9java | fbbdv |
null | 466Pascal's triangle/Puzzle | 11kotlin | p9cb6 |
package main
import (
"crypto/rand"
"math/big"
"strings"
"flag"
"math"
"fmt"
)
var lowercase = "abcdefghijklmnopqrstuvwxyz"
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var numbers = "0123456789"
var signs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"
var similar = "Il1O05S2Z"
func check(e error){
if e != nil {... | 463Password generator | 0go | vof2m |
penneysgame <- function() {
first <- sample(c("PC", "Human"), 1)
if (first == "PC") {
pc.seq <- sample(c("H", "T"), 3, replace = TRUE)
cat(paste("\nI choose first and will win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n\n"))
human.seq <- readline("Wh... | 460Penney's game | 13r | 6eo3e |
(defn fs [f s] (map f s))
(defn f1 [x] (* 2 x))
(defn f2 [x] (* x x))
(def fsf1 (partial fs f1))
(def fsf2 (partial fs f2))
(doseq [s [(range 4) (range 2 9 2)]]
(println "seq: " s)
(println " fsf1: " (fsf1 s))
(println " fsf2: " (fsf2 s))) | 468Partial function application | 6clojure | xuvwk |
use strict;
use warnings;
no warnings qw(recursion);
use Math::AnyNum qw(:overload);
use Memoize;
memoize('partitionsP');
memoize('partDiff');
sub partDiffDiff { my($n) = @_; $n%2 != 0 ? ($n+1)/2 : $n+1 }
sub partDiff { my($n) = @_; $n<2 ? 1 : partDiff($n-1) + partDiffDiff($n-1) }
sub partitionsP {
my($n) = @_;... | 465Partition function P | 2perl | xu4w8 |
class Position
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
def ==(other)
self.x == other.x &&
self.y == other.y
end
def to_s
'(%d,%d)' % [@x, @y]
end
def to_str
to_s
end
end
def isAttacking(queen, pos)
return quee... | 462Peaceful chess queen armies | 14ruby | z1qtw |
import Control.Monad
import Control.Monad.Random
import Data.List
password :: MonadRandom m => [String] -> Int -> m String
password charSets n = do
parts <- getPartition n
chars <- zipWithM replicateM parts (uniform <$> charSets)
shuffle (concat chars)
where
getPartition n = adjust <$> replicateM (k-1) (ge... | 463Password generator | 8haskell | e24ai |
typedef struct {
const char *s;
int len, prec, assoc;
} str_tok_t;
typedef struct {
const char * str;
int assoc, prec;
regex_t re;
} pat_t;
enum assoc { A_NONE, A_L, A_R };
pat_t pat_eos = {, A_NONE, 0};
pat_t pat_ops[] = {
{, A_NONE, -1},
{, A_R, 3},
{, A_R, 3},
{, A_L, 2},
{, A_L, 2},
{, A_L, 1},
{, ... | 471Parsing/Shunting-yard algorithm | 5c | l0wcy |
char** components;
int counter = 0;
typedef struct elem{
char data[10];
struct elem* left;
struct elem* right;
}node;
typedef node* tree;
int precedenceCheck(char oper1,char oper2){
return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+... | 472Parsing/RPN to infix conversion | 5c | z1jtx |
null | 467Partition an integer x into n primes | 11kotlin | 8rr0q |
from fractions import Fraction
def muller_seq(n:int) -> float:
seq = [Fraction(0), Fraction(2), Fraction(-4)]
for i in range(3, n+1):
next_value = (111 - 1130/seq[i-1]
+ 3000/(seq[i-1]*seq[i-2]))
seq.append(next_value)
return float(seq[n])
for n in [3, 4, 5, 6, 7, 8, 20, 30, 50... | 461Pathological floating point problems | 3python | bmukr |
int main()
{
int data[] = {12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519};
int largest, largest_factor = 0;
omp_set_num_threads(4);
for (int i = 0; i < 7; i++) {
int p, n = data[i];
for (p = 3; p * p <= n && n % ... | 473Parallel calculations | 5c | 6eh32 |
void pascal_low(int **mat, int n) {
int i, j;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
if (i < j)
mat[i][j] = 0;
else if (i == j || j == 0)
mat[i][j] = 1;
else
mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}
vo... | 474Pascal matrix generation | 5c | l01cy |
gcc example.c -lsqlite3 | 475Parameterized SQL statement | 5c | 7z0rg |
package main
import (
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"text/tabwriter"
) | 469Parse an IP Address | 0go | csx9g |
class TreeNode<T> {
T value;
TreeNode<T> left;
TreeNode<T> right;
TreeNode(this.value);
TreeNode map(T f(T t)) {
var node = new TreeNode(f(value));
if(left!= null) {
node.left = left.map(f);
}
if(right!= null) {
node.right = right.map(f);
}
return node;
}
void forE... | 470Parametric polymorphism | 18dart | z1kte |
enum Piece {
case empty, black, white
}
typealias Position = (Int, Int)
func place(_ m: Int, _ n: Int, pBlackQueens: inout [Position], pWhiteQueens: inout [Position]) -> Bool {
guard m!= 0 else {
return true
}
var placingBlack = true
for i in 0..<n {
inner: for j in 0..<n {
let pos = (i, j)
... | 462Peaceful chess queen armies | 17swift | tpxfl |
import java.util.*;
public class PasswordGenerator {
final static Random rand = new Random();
public static void main(String[] args) {
int num, len;
try {
if (args.length != 2)
throw new IllegalArgumentException();
len = Integer.parseInt(args[0]);
... | 463Password generator | 9java | h6cjm |
Toss = [:Heads, :Tails]
def yourChoice
puts
choice = []
3.times do
until (c = $stdin.getc.upcase) == or c ==
end
choice << (c==? Toss[0]: Toss[1])
end
puts
choice
end
loop do
puts % [*Toss, coin = Toss.sample]
if coin == Toss[0]
myC = Toss.shuffle << Toss.sample
puts
yC =... | 460Penney's game | 14ruby | 28zlw |
typedef unsigned char byte;
int matches(byte *a, byte* b) {
for (int i = 0; i < 32; i++)
if (a[i] != b[i])
return 0;
return 1;
}
byte* StringHashToByteArray(const char* s) {
byte* hash = (byte*) malloc(32);
char two[3];
two[2] = 0;
for (int i = 0; i < 32; i++) {
two[0] = s[i * 2];
two[1] = s[i * 2 + 1... | 476Parallel brute force | 5c | fbud3 |
import Data.List (isInfixOf)
import Numeric (showHex)
import Data.Char (isDigit)
data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) |
IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] |
IPv4WithPort IPChunk String | IPv4NoPort IPChunk |
IPInvalid | IPZeroSection | IPUndefinedWithPort String |
... | 469Parse an IP Address | 8haskell | p9ybt |
from itertools import islice
def posd():
count, odd = 1, 3
while True:
yield count
yield odd
count, odd = count + 1, odd + 2
def pos_gen():
val = 1
diff = posd()
while True:
yield val
val += next(diff)
def plus_minus():
n, sign = 0, [1, 1... | 465Partition function P | 3python | q5gxi |
String.prototype.shuffle = function() {
return this.split('').sort(() => Math.random() - .5).join('');
}
function createPwd(opts = {}) {
let len = opts.len || 5, | 463Password generator | 10javascript | al510 |
func perms<T>(var ar: [T]) -> [[T]] {
return heaps(&ar, ar.count)
}
func heaps<T>(inout ar: [T], n: Int) -> [[T]] {
return n == 1? [ar]:
Swift.reduce(0..<n, [[T]]()) {
(var shuffles, i) in
shuffles.extend(heaps(&ar, n - 1))
swap(&ar[n% 2 == 0? i: 0], &ar[n - 1])
return shuffles
}
}
p... | 456Permutations | 17swift | uicvg |
extern crate rand;
use std::io::{stdin, stdout, Write};
use std::thread;
use std::time::Duration;
use rand::Rng;
fn toss_coin<R: Rng>(rng: &mut R, print: bool) -> char {
let c = if rng.gen() { 'H' } else { 'T' };
if print {
print!("{}", c);
stdout().flush().expect("Could not flush stdout");
... | 460Penney's game | 15rust | vo32t |
package main
import "fmt"
func average(c intCollection) float64 {
var sum, count int
c.mapElements(func(n int) {
sum += n
count++
})
return float64(sum) / float64(count)
}
func main() {
t1 := new(binaryTree)
t2 := new(bTree)
a1 := average(t1)
a2 := average(t2)
fmt.... | 470Parametric polymorphism | 0go | wvceg |
class Tree<T> {
T value
Tree<T> left
Tree<T> right
Tree(T value = null, Tree<T> left = null, Tree<T> right = null) {
this.value = value
this.left = left
this.right = right
}
void replaceAll(T value) {
this.value = value
left?.replaceAll(value)
ri... | 470Parametric polymorphism | 7groovy | bm3ky |
use ntheory ":all";
sub prime_partition {
my($num, $parts) = @_;
return is_prime($num) ? [$num] : undef if $parts == 1;
my @p = @{primes($num)};
my $r;
forcomb { lastfor, $r = [@p[@_]] if vecsum(@p[@_]) == $num; } @p, $parts;
$r;
}
foreach my $test ([18,2], [19,3], [20,4], [99807,1], [99809,1], [2017,24],... | 467Partition an integer x into n primes | 2perl | 4dd5d |
my $rows = 5;
my @tri = map { [ map { {x=>0,z=>0,v=>0,rhs=>undef} } 1..$_ ] } 1..$rows;
$tri[0][0]{rhs} = 151;
$tri[2][0]{rhs} = 40;
$tri[4][0]{x} = 1;
$tri[4][1]{v} = 11;
$tri[4][2]{x} = 1;
$tri[4][2]{z} = 1;
$tri[4][3]{v} = 4;
$tri[4][4]{z} = 1;
for my $row ( reverse 0..@tri-2 ) {
for my $col ( 0..@{$tri[$row]}... | 466Pascal's triangle/Puzzle | 2perl | ywx6u |
(use '[clojure.contrib.lazy-seqs:only [primes]])
(defn lpf [n]
[n (or (last
(for [p (take-while #(<= (* % %) n) primes)
:when (zero? (rem n p))]
p))
1)])
(->> (range 2 100000)
(pmap lpf)
(apply max-key second)
println
time) | 473Parallel calculations | 6clojure | l0acb |
int pancake(int n) {
int gap = 2, sum = 2, adj = -1;
while (sum < n) {
adj++;
gap = gap * 2 - 1;
sum += gap;
}
return n + adj;
}
int main() {
int i, j;
for (i = 0; i < 4; i++) {
for (j = 1; j < 6; j++) {
int n = i * 5 + j;
printf(, n, panc... | 477Pancake numbers | 5c | 0gyst |
(defn binomial-coeff [n k]
(reduce #(quot (* %1 (inc (- n %2))) %2)
1
(range 1 (inc k))))
(defn pascal-upper [n]
(map
(fn [i]
(map (fn [j]
(binomial-coeff j i))
(range n)))
(range n)))
(defn pascal-lower [n]
(map
(fn [i]
(map (fn [j]
(bino... | 474Pascal matrix generation | 6clojure | 4dq5o |
(require '[clojure.java.jdbc:as sql])
(def db {:classname "org.h2.Driver"
:subprotocol "h2:file"
:subname "db/my-dbname"})
(sql/update! db:players {:name "Smith, Steve":score 42:active true} ["jerseyNum =?" 99])
(sql/execute! db ["UPDATE players SET name =?, score =?, active =? WHERE jerseyNum =?" "... | 475Parameterized SQL statement | 6clojure | p9dbd |
data Tree a = Empty | Node a (Tree a) (Tree a)
mapTree :: (a -> b) -> Tree a -> Tree b
mapTree f Empty = Empty
mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r) | 470Parametric polymorphism | 8haskell | 6ep3k |
package main
import "fmt" | 468Partial function application | 0go | 6ea3p |
null | 465Partition function P | 15rust | 8rj07 |
import BigInt
func partitions(n: Int) -> BigInt {
var p = [BigInt(1)]
for i in 1...n {
var num = BigInt(0)
var k = 1
while true {
var j = (k * (3 * k - 1)) / 2
if j > i {
break
}
if k & 1 == 1 {
num += p[i - j]
} else {
num -= p[i - j]
}
... | 465Partition function P | 17swift | s4rqt |
null | 463Password generator | 11kotlin | 4d357 |
ar = [0, 2, -4]
100.times{ar << (111 - 1130.quo(ar[-1])+ 3000.quo(ar[-1]*ar[-2])) }
[3, 4, 5, 6, 7, 8, 20, 30, 50, 100].each do |n|
puts % [n, ar[n]]
end | 461Pathological floating point problems | 14ruby | 1c4pw |
(ns rosetta.brute-force
(:require [clojure.math.combinatorics:refer [selections]])
(:import [java.util Arrays]
[java.security MessageDigest]))
(def targets
["1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad"
"3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b"
... | 476Parallel brute force | 6clojure | yw76b |
typedef unsigned long long xint;
xint rooted[MAX_N] = {1, 1, 0};
xint unrooted[MAX_N] = {1, 1, 0};
xint choose(xint m, xint k)
{
xint i, r;
if (k == 1) return m;
for (r = m, i = 1; i < k; i++)
r = r * (m + i) / (i + 1);
return r;
}
void tree(xint br, xint n, xint cnt, xint sum, xint l)
{
xint b, c, m, s;
... | 478Paraffins | 5c | dklnv |
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, _ := sql.Open("sqlite3", "rc.db")
defer db.Close()
db.Exec(`create table players (name, score, active, jerseyNum)`)
db.Exec(`insert into players values ("",0,0,"99")`)
db.Exec(`insert into p... | 475Parameterized SQL statement | 0go | dkune |
module Main (main) where
import Database.HDBC (IConnection, commit, run, toSql)
updatePlayers :: IConnection a => a -> String -> Int -> Bool -> Int -> IO Bool
updatePlayers conn name score active jerseyNum = do
rowCount <- run conn
"UPDATE players\
\ SET name =?, score =?, active =?\
... | 475Parameterized SQL statement | 8haskell | 5nwug |
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ParseIPAddress {
public static void main(String[] args) {
String [] tests = new String[] {"192.168.0.1", "127.0.0.1", "256.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "[32e::12f]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4... | 469Parse an IP Address | 9java | rtdg0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.