code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
function swap(arr) { var tmp = arr[0]; arr[0] = arr[1]; arr[1] = tmp; }
786Generic swap
10javascript
wz9e2
def gcdR gcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m: m%n == 0 ? n: gcdR(n, m%n) }
787Greatest common divisor
7groovy
mjpy5
#![feature(core)] fn sumsqd(mut n: i32) -> i32 { let mut sq = 0; while n > 0 { let d = n% 10; sq += d*d; n /= 10 } sq } use std::num::Int; fn cycle<T: Int>(a: T, f: fn(T) -> T) -> T { let mut t = a; let mut h = f(a); while t!= h { t = f(t); h = f(f(h)) } t } fn ishappy(n: i32) -> bool { cycle(n, sumsqd) == 1 } fn main() { let happy = std::iter::count(1, 1) .filter(|&n| ishappy(n)) .take(8) .collect::<Vec<i32>>(); println!("{:?}", happy) }
771Happy numbers
15rust
korh5
import java.util.ArrayDeque fun hailstone(n: Int): ArrayDeque<Int> { val hails = when { n == 1 -> ArrayDeque<Int>() n% 2 == 0 -> hailstone(n / 2) else -> hailstone(3 * n + 1) } hails.addFirst(n) return hails } fun main(args: Array<String>) { val hail27 = hailstone(27) fun showSeq(s: List<Int>) = s.map { it.toString() }.reduce { a, b -> a + ", " + b } println("Hailstone sequence for 27 is " + showSeq(hail27.take(3)) + " ... " + showSeq(hail27.drop(hail27.size - 3)) + " with length ${hail27.size}.") var longestHail = hailstone(1) for (x in 1..99999) longestHail = arrayOf(hailstone(x), longestHail).maxBy { it.size }?: longestHail println("${longestHail.first} is the number less than 100000 with " + "the longest sequence, having length ${longestHail.size}.") }
785Hailstone sequence
11kotlin
t5hf0
gcd :: (Integral a) => a -> a -> a gcd x y = gcd_ (abs x) (abs y) where gcd_ a 0 = a gcd_ a b = gcd_ b (a `rem` b)
787Greatest common divisor
8haskell
etyai
scala> def isHappy(n: Int) = { | new Iterator[Int] { | val seen = scala.collection.mutable.Set[Int]() | var curr = n | def next = { | val res = curr | curr = res.toString.map(_.asDigit).map(n => n * n).sum | seen += res | res | } | def hasNext = !seen.contains(curr) | }.toList.last == 1 | } isHappy: (n: Int)Boolean scala> Iterator from 1 filter isHappy take 8 foreach println 1 7 10 13 19 23 28 31
771Happy numbers
16scala
1dhpf
null
784Greatest element of a list
1lua
etcac
null
786Generic swap
11kotlin
rqigo
public static long gcd(long a, long b){ long factor= Math.min(a, b); for(long loop= factor;loop > 1;loop--){ if(a % loop == 0 && b % loop == 0){ return loop; } } return 1; }
787Greatest common divisor
9java
h8djm
function gcd(a,b) { a = Math.abs(a); b = Math.abs(b); if (b > a) { var temp = a; a = b; b = temp; } while (true) { a %= b; if (a === 0) { return b; } b %= a; if (b === 0) { return a; } } }
787Greatest common divisor
10javascript
af610
function hailstone( n, print_numbers ) local n_iter = 1 while n ~= 1 do if print_numbers then print( n ) end if n % 2 == 0 then n = n / 2 else n = 3 * n + 1 end n_iter = n_iter + 1 end if print_numbers then print( n ) end return n_iter; end hailstone( 27, true ) max_i, max_iter = 0, 0 for i = 1, 100000 do num = hailstone( i, false ) if num >= max_iter then max_i = i max_iter = num end end print( string.format( "Needed%d iterations for the number%d.\n", max_iter, max_i ) )
785Hailstone sequence
1lua
z4kty
tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a% b)
787Greatest common divisor
11kotlin
4w057
func isHappyNumber(var n:Int) -> Bool { var cycle = [Int]() while n!= 1 &&!cycle.contains(n) { cycle.append(n) var m = 0 while n > 0 { let d = n% 10 m += d * d n = (n - d) / 10 } n = m } return n == 1 } var found = 0 var count = 0 while found!= 8 { if isHappyNumber(count) { print(count) found++ } count++ }
771Happy numbers
17swift
j0474
print "Hello world!"
755Hello world/Text
1lua
oll8h
x, y = y, x
786Generic swap
1lua
7snru
function gcd(a,b) if b ~= 0 then return gcd(b, a % b) else return math.abs(a) end end function demo(a,b) print("GCD of " .. a .. " and " .. b .. " is " .. gcd(a, b)) end demo(100, 5) demo(5, 100) demo(7, 23)
787Greatest common divisor
1lua
gx84j
sub max { my $max = shift; for (@_) { $max = $_ if $_ > $max } return $max; }
784Greatest element of a list
2perl
9hwmn
max($values)
784Greatest element of a list
12php
wzlep
use warnings; use strict; my @h = hailstone(27); print "Length of hailstone(27) = " . scalar @h . "\n"; print "[" . join(", ", @h[0 .. 3], "...", @h[-4 .. -1]) . "]\n"; my ($max, $n) = (0, 0); for my $x (1 .. 99_999) { @h = hailstone($x); if (scalar @h > $max) { ($max, $n) = (scalar @h, $x); } } print "Max length $max was found for hailstone($n) for numbers < 100_000\n"; sub hailstone { my ($n) = @_; my @sequence = ($n); while ($n > 1) { if ($n % 2 == 0) { $n = int($n / 2); } else { $n = $n * 3 + 1; } push @sequence, $n; } return @sequence; }
785Hailstone sequence
2perl
kozhc
max(values)
784Greatest element of a list
3python
ckx9q
v <- c(1, 2, 100, 50, 0) print(max(v))
784Greatest element of a list
13r
6r13e
function hailstone($n,$seq=array()){ $sequence = $seq; $sequence[] = $n; if($n == 1){ return $sequence; }else{ $n = ($n%2==0)? $n/2 : (3*$n)+1; return hailstone($n, $sequence); } } $result = hailstone(27); echo count($result) . ' Elements.<br>'; echo 'Starting with: ' . implode(,array_slice($result,0,4)) .' and ending with: ' . implode(,array_slice($result,count($result)-4)) . '<br>'; $maxResult = array(0); for($i=1;$i<=100000;$i++){ $result = count(hailstone($i)); if($result > max($maxResult)){ $maxResult = array($i=>$result); } } foreach($maxResult as $key => $val){ echo 'Number < 100000 with longest Hailstone seq.: ' . $key . ' with length of ' . $val; }
785Hailstone sequence
12php
3gbzq
values.max
784Greatest element of a list
14ruby
2pslw
fn main() { let nums = [1,2,39,34,20]; println!("{:?}", nums.iter().max()); println!("{}", nums.iter().max().unwrap()); }
784Greatest element of a list
15rust
v102t
($y, $x) = ($x, $y);
786Generic swap
2perl
dvrnw
def noSweat(list: Int*) = list.max
784Greatest element of a list
16scala
4wi50
function swap(&$a, &$b) { list($a, $b) = array($b, $a); }
786Generic swap
12php
j0d7z
sub gcd_iter($$) { my ($u, $v) = @_; while ($v) { ($u, $v) = ($v, $u % $v); } return abs($u); }
787Greatest common divisor
2perl
il5o3
def hailstone(n): seq = [n] while n>1: n = 3*n + 1 if n & 1 else n seq.append(n) return seq if __name__ == '__main__': h = hailstone(27) assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1] print(% max((len(hailstone(i)), i) for i in range(1,100000)))
785Hailstone sequence
3python
bi3kr
function gcdIter($n, $m) { while(true) { if($n == $m) { return $m; } if($n > $m) { $n -= $m; } else { $m -= $n; } } }
787Greatest common divisor
12php
rqoge
makeHailstone <- function(n){ hseq <- n while (hseq[length(hseq)] > 1){ current.value <- hseq[length(hseq)] if (current.value %% 2 == 0){ next.value <- current.value / 2 } else { next.value <- (3 * current.value) + 1 } hseq <- append(hseq, next.value) } return(list(hseq=hseq, seq.length=length(hseq))) } twenty.seven <- makeHailstone(27) twenty.seven$hseq twenty.seven$seq.length max.length <- 0; lower.bound <- 1; upper.bound <- 100000 for (index in lower.bound:upper.bound){ current.hseq <- makeHailstone(index) if (current.hseq$seq.length > max.length){ max.length <- current.hseq$seq.length max.index <- index } } cat("Between ", lower.bound, " and ", upper.bound, ", the input of ", max.index, " gives the longest hailstone sequence, which has length ", max.length, ". \n", sep="")
785Hailstone sequence
13r
7sdry
if let x = [4,3,5,9,2,3].maxElement() { print(x)
784Greatest element of a list
17swift
lbqc2
a, b = b, a
786Generic swap
3python
fu7de
swap <- function(name1, name2, envir = parent.env(environment())) { temp <- get(name1, pos = envir) assign(name1, get(name2, pos = envir), pos = envir) assign(name2, temp, pos = envir) }
786Generic swap
13r
oc584
from fractions import gcd
787Greatest common divisor
3python
n24iz
def hailstone n seq = [n] until n == 1 n = (n.even?)? (n / 2): (3 * n + 1) seq << n end seq end puts hs27 = hailstone 27 p [hs27.length, hs27[0..3], hs27[-4..-1]] n = (1 ... 100_000).max_by{|n| hailstone(n).length} puts puts
785Hailstone sequence
14ruby
1dypw
"%gcd%" <- function(u, v) { ifelse(u%% v!= 0, v%gcd% (u%%v), v) }
787Greatest common divisor
13r
0m2sg
fn hailstone(start: u32) -> Vec<u32> { let mut res = Vec::new(); let mut next = start; res.push(start); while next!= 1 { next = if next% 2 == 0 { next/2 } else { 3*next+1 }; res.push(next); } res } fn main() { let test_num = 27; let test_hailseq = hailstone(test_num); println!("For {} number of elements is {} ", test_num, test_hailseq.len()); let fst_slice = test_hailseq[0..4].iter() .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); let last_slice = test_hailseq[test_hailseq.len()-4..].iter() .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); println!(" hailstone starting with {} ending with {} ", fst_slice, last_slice); let max_range = 100000; let mut max_len = 0; let mut max_seed = 0; for i_seed in 1..max_range { let i_len = hailstone(i_seed).len(); if i_len > max_len { max_len = i_len; max_seed = i_seed; } } println!("Longest sequence is {} element long for seed {}", max_len, max_seed); }
785Hailstone sequence
15rust
afm14
struct gen64 { cothread_t giver; cothread_t taker; int64_t given; void (*free)(struct gen64 *); void *garbage; }; inline void yield64(struct gen64 *gen, int64_t value) { gen->given = value; co_switch(gen->taker); } inline int64_t next64(struct gen64 *gen) { gen->taker = co_active(); co_switch(gen->giver); return gen->given; } static void gen64_free(struct gen64 *gen) { co_delete(gen->giver); } struct gen64 *entry64; inline void gen64_init(struct gen64 *gen, void (*entry)(void)) { if ((gen->giver = co_create(4096, entry)) == NULL) { fputs(, stderr); exit(1); } gen->free = gen64_free; entry64 = gen; } void powers(struct gen64 *gen, int64_t m) { int64_t base, exponent, n, result; for (n = 0;; n++) { base = n; exponent = m; for (result = 1; exponent != 0; exponent >>= 1) { if (exponent & 1) result *= base; base *= base; } yield64(gen, result); } } ENTRY(enter_squares, powers(entry64, 2)) ENTRY(enter_cubes, powers(entry64, 3)) struct swc { struct gen64 cubes; struct gen64 squares; void (*old_free)(struct gen64 *); }; static void swc_free(struct gen64 *gen) { struct swc *f = gen->garbage; f->cubes.free(&f->cubes); f->squares.free(&f->squares); f->old_free(gen); } void squares_without_cubes(struct gen64 *gen) { struct swc f; int64_t c, s; gen64_init(&f.cubes, enter_cubes); c = next64(&f.cubes); gen64_init(&f.squares, enter_squares); s = next64(&f.squares); f.old_free = gen->free; gen->garbage = &f; gen->free = swc_free; for (;;) { while (c < s) c = next64(&f.cubes); if (c != s) yield64(gen, s); s = next64(&f.squares); } } ENTRY(enter_squares_without_cubes, squares_without_cubes(entry64)) int main() { struct gen64 gen; int i; gen64_init(&gen, enter_squares_without_cubes); for (i = 0; i < 20; i++) next64(&gen); for (i = 0; i < 9; i++) printf( PRId64 , next64(&gen)); printf( PRId64 , next64(&gen)); gen.free(&gen); return 0; }
788Generator/Exponential
5c
ocv80
a, b = b, a
786Generic swap
14ruby
z4htw
object HailstoneSequence extends App { def hailstone(n: Int): Stream[Int] = n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) val nr = args.headOption.map(_.toInt).getOrElse(27) val collatz = hailstone(nr) println(s"Use the routine to show that the hailstone sequence for the number: $nr.") println(collatz.toList) println(s"It has ${collatz.length} elements.") println println( "Compute the number < 100,000, which has the longest hailstone sequence with that sequence's length.") val (n, len) = (1 until 100000).map(n => (n, hailstone(n).length)).maxBy(_._2) println(s"Longest hailstone sequence length= $len occurring with number $n.") }
785Hailstone sequence
16scala
x3lwg
fn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) { std::mem::swap(var1, var2) }
786Generic swap
15rust
3gkz8
40902.gcd(24140)
787Greatest common divisor
14ruby
furdr
typedef int bool; char grid[8][8]; void placeKings() { int r1, r2, c1, c2; for (;;) { r1 = rand() % 8; c1 = rand() % 8; r2 = rand() % 8; c2 = rand() % 8; if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) { grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; return; } } } void placePieces(const char *pieces, bool isPawn) { int n, r, c; int numToPlace = rand() % strlen(pieces); for (n = 0; n < numToPlace; ++n) { do { r = rand() % 8; c = rand() % 8; } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces[n]; } } void toFen() { char fen[80], ch; int r, c, countEmpty = 0, index = 0; for (r = 0; r < 8; ++r) { for (c = 0; c < 8; ++c) { ch = grid[r][c]; printf(, ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++] = ch; } } if (countEmpty > 0) { fen[index++] = countEmpty + 48; countEmpty = 0; } fen[index++]= '/'; printf(); } strcpy(fen + index, ); printf(, fen); } char *createFen() { placeKings(); placePieces(, TRUE); placePieces(, TRUE); placePieces(, FALSE); placePieces(, FALSE); toFen(); } int main() { srand(time(NULL)); createFen(); return 0; }
789Generate random chess position
5c
1dtpj
def swap[A,B](a: A, b: B): (B, A) = (b, a)
786Generic swap
16scala
mj1yc
(defn powers [m] (for [n (iterate inc 1)] (reduce * (repeat m n))))) (def squares (powers 2)) (take 5 squares)
788Generator/Exponential
6clojure
t5rfv
extern crate num; use num::integer::gcd;
787Greatest common divisor
15rust
t57fd
def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)
787Greatest common divisor
16scala
6rk31
char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; printf(,rank); { setlocale(LC_ALL,); printf(); for(i=0;i<8;i++){ if(rank[i]=='K') printf(,(wint_t)9812); else if(rank[i]=='Q') printf(,(wint_t)9813); else if(rank[i]=='R') printf(,(wint_t)9814); else if(rank[i]=='B') printf(,(wint_t)9815); if(rank[i]=='N') printf(,(wint_t)9816); } } } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
790Generate Chess960 starting position
5c
t54f4
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) var grid [8][8]byte func abs(i int) int { if i >= 0 { return i } else { return -i } } func createFen() string { placeKings() placePieces("PPPPPPPP", true) placePieces("pppppppp", true) placePieces("RNBQBNR", false) placePieces("rnbqbnr", false) return toFen() } func placeKings() { for { r1 := rand.Intn(8) c1 := rand.Intn(8) r2 := rand.Intn(8) c2 := rand.Intn(8) if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 { grid[r1][c1] = 'K' grid[r2][c2] = 'k' return } } } func placePieces(pieces string, isPawn bool) { numToPlace := rand.Intn(len(pieces)) for n := 0; n < numToPlace; n++ { var r, c int for { r = rand.Intn(8) c = rand.Intn(8) if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) { break } } grid[r][c] = pieces[n] } } func toFen() string { var fen strings.Builder countEmpty := 0 for r := 0; r < 8; r++ { for c := 0; c < 8; c++ { ch := grid[r][c] if ch == '\000' { ch = '.' } fmt.Printf("%2c ", ch) if ch == '.' { countEmpty++ } else { if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteByte(ch) } } if countEmpty > 0 { fen.WriteString(strconv.Itoa(countEmpty)) countEmpty = 0 } fen.WriteString("/") fmt.Println() } fen.WriteString(" w - - 0 1") return fen.String() } func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(createFen()) }
789Generate random chess position
0go
y7h64
module RandomChess ( placeKings , placePawns , placeRemaining , emptyBoard , toFen , ChessBoard , Square (..) , BoardState (..) , getBoard ) where import Control.Monad.State (State, get, gets, put) import Data.List (find, sortBy) import System.Random (Random, RandomGen, StdGen, random, randomR) type Pos = (Char, Int) type ChessBoard = [(Square, Pos)] data PieceRank = King | Queen | Rook | Bishop | Knight | Pawn deriving (Enum, Bounded, Show, Eq, Ord) data PieceColor = Black | White deriving (Enum, Bounded, Show, Eq, Ord) data Square = ChessPiece PieceRank PieceColor | EmptySquare deriving (Eq, Ord) type PieceCount = [(Square, Int)] data BoardState = BoardState { board :: ChessBoard , generator :: StdGen } instance Show Square where show (ChessPiece King Black) = "" show (ChessPiece Queen Black) = "" show (ChessPiece Rook Black) = "" show (ChessPiece Bishop Black) = "" show (ChessPiece Knight Black) = "" show (ChessPiece Pawn Black) = "" show (ChessPiece King White) = "" show (ChessPiece Queen White) = "" show (ChessPiece Rook White) = "" show (ChessPiece Bishop White) = "" show (ChessPiece Knight White) = "" show (ChessPiece Pawn White) = "" show EmptySquare = " " instance Random PieceRank where randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of (x, g'') -> (toEnum x, g'') random = randomR (minBound, maxBound) instance Random PieceColor where randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of (x, g'') -> (toEnum x, g'') random = randomR (minBound, maxBound) fullBoard :: PieceCount fullBoard = [ (ChessPiece King Black , 1) , (ChessPiece Queen Black , 1) , (ChessPiece Rook Black , 2) , (ChessPiece Bishop Black, 2) , (ChessPiece Knight Black, 2) , (ChessPiece Pawn Black , 8) , (ChessPiece King White , 1) , (ChessPiece Queen White , 1) , (ChessPiece Rook White , 2) , (ChessPiece Bishop White, 2) , (ChessPiece Knight White, 2) , (ChessPiece Pawn White , 8) , (EmptySquare , 32) ] emptyBoard :: ChessBoard emptyBoard = fmap (EmptySquare,) . (,) <$> ['a'..'h'] <*> [1..8] replaceSquareByPos :: (Square, Pos) -> ChessBoard -> ChessBoard replaceSquareByPos e@(_, p) = fmap (\x -> if p == snd x then e else x) isPosOccupied :: Pos -> ChessBoard -> Bool isPosOccupied p = occupied . find (\x -> p == snd x) where occupied (Just (EmptySquare, _)) = False occupied _ = True isAdjacent :: Pos -> Pos -> Bool isAdjacent (x1, y1) (x2, y2) = let upOrDown = (pred y1 == y2 || succ y1 == y2) leftOrRight = (pred x1 == x2 || succ x1 == x2) in (x2 == x1 && upOrDown) || (pred x1 == x2 && upOrDown) || (succ x1 == x2 && upOrDown) || (leftOrRight && y1 == y2) fen :: Square -> String fen (ChessPiece King Black) = "k" fen (ChessPiece Queen Black) = "q" fen (ChessPiece Rook Black) = "r" fen (ChessPiece Bishop Black) = "b" fen (ChessPiece Knight Black) = "n" fen (ChessPiece Pawn Black) = "p" fen (ChessPiece King White) = "K" fen (ChessPiece Queen White) = "Q" fen (ChessPiece Rook White) = "R" fen (ChessPiece Bishop White) = "B" fen (ChessPiece Knight White) = "N" fen (ChessPiece Pawn White) = "P" boardSort :: (Square, Pos) -> (Square, Pos) -> Ordering boardSort (_, (x1, y1)) (_, (x2, y2)) | y1 < y2 = GT | y1 > y2 = LT | y1 == y2 = compare x1 x2 toFen :: ChessBoard -> String toFen [] = " w - - 0 1" <> [] toFen b = scanRow (fst <$> take 8 b) 0 where scanRow [] 0 = nextRow scanRow [] n = show n <> nextRow scanRow (EmptySquare:xs) n = scanRow xs (succ n) scanRow (x:xs) 0 = nextPiece x xs scanRow (x:xs) n = show n <> nextPiece x xs nextRow = "/" <> toFen (drop 8 b) nextPiece x xs = fen x <> scanRow xs 0 withStateGen :: (StdGen -> (a, StdGen)) -> State BoardState a withStateGen f = do currentState <- get let gen1 = generator currentState let (x, gen2) = f gen1 put (currentState {generator = gen2}) pure x randomPos :: State BoardState Pos randomPos = do boardState <- gets board chr <- withStateGen (randomR ('a', 'h')) num <- withStateGen (randomR (1, 8)) let pos = (chr, num) if isPosOccupied pos boardState then randomPos else pure pos randomPiece :: State BoardState Square randomPiece = ChessPiece <$> withStateGen random <*> withStateGen random placeKings :: State BoardState () placeKings = do currentState <- get p1 <- randomPos p2 <- randomPos if p1 `isAdjacent` p2 || p1 == p2 then placeKings else do let updatedBoard = replaceSquareByPos (ChessPiece King White, p1) $ replaceSquareByPos (ChessPiece King Black, p2) (board currentState) put currentState { board = updatedBoard } placePawns :: State BoardState () placePawns = withStateGen (randomR (1, 16)) >>= go where go :: Int -> State BoardState () go 0 = pure () go n = do currentState <- get pos <- randomPos color <- withStateGen random let pawn = ChessPiece Pawn color let currentBoard = board currentState if promoted color == snd pos || isPosOccupied pos currentBoard || enpassant color == snd pos || firstPos color == snd pos then go n else do put currentState { board = replaceSquareByPos (pawn, pos) currentBoard } go $ pred n promoted White = 8 promoted Black = 1 enpassant White = 5 enpassant Black = 4 firstPos White = 1 firstPos Black = 8 placeRemaining :: State BoardState () placeRemaining = withStateGen (randomR (5, sum $ fmap snd remaining)) >>= go remaining where remaining = filter (\case (ChessPiece King _, _) -> False (ChessPiece Pawn _, _) -> False (EmptySquare, _) -> False _ -> True) fullBoard go :: PieceCount -> Int -> State BoardState () go _ 0 = pure () go remaining n = do currentState <- get let currentBoard = board currentState position <- randomPos piece <- randomPiece if not (isPermitted piece) || isPosOccupied position currentBoard then go remaining n else do let updatedBoard = replaceSquareByPos (piece, position) currentBoard put currentState { board = updatedBoard } go (consume piece remaining) (pred n) where isPermitted p = case find ((==p) . fst) remaining of Just (_, count) -> count > 0 Nothing -> False consume p'' = fmap (\(p, c) -> if p == p'' then (p, pred c) else (p, c)) getBoard :: State BoardState ChessBoard getBoard = gets (sortBy boardSort . board)
789Generate random chess position
8haskell
h8iju
(ns c960.core (:gen-class) (:require [clojure.string:as s])) (def starting-rank [\ \ \ \ \ \ \ \]) (defn bishops-legal? "True if Bishops are odd number of indicies apart" [rank] (odd? (apply - (cons 0 (sort > (keep-indexed #(when (= \ %2) %1) rank)))))) (defn king-legal? "True if the king is between two rooks" [rank] (let [king-&-rooks (filter #{\ \} rank)] (and (= 3 (count king-&-rooks)) (= \u2654 (second king-&-rooks))))) (defn c960 "Return a legal rank for c960 chess" ([] (c960 1)) ([n] (->> #(shuffle starting-rank) repeatedly (filter #(and (king-legal? %) (bishops-legal? %))) (take n) (map #(s/join ", " %))))) (c960) (c960) (c960 4)
790Generate Chess960 starting position
6clojure
mjhyq
func hailstone(var n:Int) -> [Int] { var arr = [n] while n!= 1 { if n% 2 == 0 { n /= 2 } else { n = (3 * n) + 1 } arr.append(n) } return arr } let n = hailstone(27) println("hailstone(27): \(n[0...3]) ... \(n[n.count-4...n.count-1]) for a count of \(n.count).") var longest = (n: 1, len: 1) for i in 1...100_000 { let new = hailstone(i) if new.count > longest.len { longest = (i, new.count) } } println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")
785Hailstone sequence
17swift
pn6bl
func swap<T>(inout a: T, inout b: T) { (a, b) = (b, a) }
786Generic swap
17swift
t5jfl
import static java.lang.Math.abs; import java.util.Random; public class Fen { static Random rand = new Random(); public static void main(String[] args) { System.out.println(createFen()); } static String createFen() { char[][] grid = new char[8][8]; placeKings(grid); placePieces(grid, "PPPPPPPP", true); placePieces(grid, "pppppppp", true); placePieces(grid, "RNBQBNR", false); placePieces(grid, "rnbqbnr", false); return toFen(grid); } static void placeKings(char[][] grid) { int r1, c1, r2, c2; while (true) { r1 = rand.nextInt(8); c1 = rand.nextInt(8); r2 = rand.nextInt(8); c2 = rand.nextInt(8); if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) break; } grid[r1][c1] = 'K'; grid[r2][c2] = 'k'; } static void placePieces(char[][] grid, String pieces, boolean isPawn) { int numToPlace = rand.nextInt(pieces.length()); for (int n = 0; n < numToPlace; n++) { int r, c; do { r = rand.nextInt(8); c = rand.nextInt(8); } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } static String toFen(char[][] grid) { StringBuilder fen = new StringBuilder(); int countEmpty = 0; for (int r = 0; r < 8; r++) { for (int c = 0; c < 8; c++) { char ch = grid[r][c]; System.out.printf("%2c ", ch == 0 ? '.' : ch); if (ch == 0) { countEmpty++; } else { if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append(ch); } } if (countEmpty > 0) { fen.append(countEmpty); countEmpty = 0; } fen.append("/"); System.out.println(); } return fen.append(" w - - 0 1").toString(); } }
789Generate random chess position
9java
5exuf
Array.prototype.shuffle = function() { for (let i = this.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } } function randomFEN() { let board = []; for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' ')); function getRandPos() { return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]; } function isOccupied(pos) { return board[pos[0]][pos[1]] != '.'; } function isAdjacent(pos1, pos2) { if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1) if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1) return true; return false; }
789Generate random chess position
10javascript
j0o7n
struct replace_info { int n; char *text; }; int compare(const void *a, const void *b) { struct replace_info *x = (struct replace_info *) a; struct replace_info *y = (struct replace_info *) b; return x->n - y->n; } void generic_fizz_buzz(int max, struct replace_info *info, int info_length) { int i, it; int found_word; for (i = 1; i < max; ++i) { found_word = 0; for (it = 0; it < info_length; ++it) { if (0 == i % info[it].n) { printf(, info[it].text); found_word = 1; } } if (0 == found_word) printf(, i); printf(); } } int main(void) { struct replace_info info[3] = { {5, }, {7, }, {3, } }; qsort(info, 3, sizeof(struct replace_info), compare); generic_fizz_buzz(20, info, 3); return 0; }
791General FizzBuzz
5c
2pplo
DROP TABLE tbl; CREATE TABLE tbl ( u NUMBER, v NUMBER ); INSERT INTO tbl ( u, v ) VALUES ( 20, 50 ); INSERT INTO tbl ( u, v ) VALUES ( 21, 50 ); INSERT INTO tbl ( u, v ) VALUES ( 21, 51 ); INSERT INTO tbl ( u, v ) VALUES ( 22, 50 ); INSERT INTO tbl ( u, v ) VALUES ( 22, 55 ); commit; WITH FUNCTION gcd ( ui IN NUMBER, vi IN NUMBER ) RETURN NUMBER IS u NUMBER:= ui; v NUMBER:= vi; t NUMBER; BEGIN while v > 0 loop t:= u; u:= v; v:= MOD(t, v ); END loop; RETURN abs(u); END gcd; SELECT u, v, gcd ( u, v ) FROM tbl /
787Greatest common divisor
19sql
9h1m6
null
789Generate random chess position
11kotlin
ckp98
int gjinv (double *a, int n, double *b) { int i, j, k, p; double f, g, tol; if (n < 1) return -1; f = 0.; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { g = a[j+i*n]; f += g * g; } } f = sqrt(f); tol = f * 2.2204460492503131e-016; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { b[j+i*n] = (i == j) ? 1. : 0.; } } for (k = 0; k < n; ++k) { f = fabs(a[k+k*n]); p = k; for (i = k+1; i < n; ++i) { g = fabs(a[k+i*n]); if (g > f) { f = g; p = i; } } if (f < tol) return 1; if (p != k) { for (j = k; j < n; ++j) { f = a[j+k*n]; a[j+k*n] = a[j+p*n]; a[j+p*n] = f; } for (j = 0; j < n; ++j) { f = b[j+k*n]; b[j+k*n] = b[j+p*n]; b[j+p*n] = f; } } f = 1. / a[k+k*n]; for (j = k; j < n; ++j) a[j+k*n] *= f; for (j = 0; j < n; ++j) b[j+k*n] *= f; for (i = 0; i < n; ++i) { if (i == k) continue; f = a[k+i*n]; for (j = k; j < n; ++j) a[j+i*n] -= a[j+k*n] * f; for (j = 0; j < n; ++j) b[j+i*n] -= b[j+k*n] * f; } } return 0; }
792Gauss-Jordan matrix inversion
5c
pniby
null
787Greatest common divisor
17swift
dvgnh
void generateGaps(unsigned long long int start,int count){ int counter = 0; unsigned long long int i = start; char str[100]; printf(,count,start); while(counter<count){ sprintf(str,,i); if((i%(10*(str[0]-'0') + i%10))==0L){ printf(,counter+1,i); counter++; } i++; } } int main() { unsigned long long int i = 100; int count = 0; char str[21]; generateGaps(100,30); printf(); generateGaps(1000000,15); printf(); generateGaps(1000000000,15); printf(); return 0; }
793Gapful numbers
5c
wzfec
use strict; use warnings; use feature 'say'; use utf8; use List::AllUtils <shuffle any natatime>; sub pick1 { return @_[rand @_] } sub gen_FEN { my $n = 1 + int rand 31; my @n = (shuffle(0 .. 63))[1 .. $n]; my @kings; KINGS: { for my $a (@n) { for my $b (@n) { next unless $a != $b && abs(int($a/8) - int($b/8)) > 1 || abs($a%8 - $b%8) > 1; @kings = ($a, $b); last KINGS; } die 'No good place for kings!'; } } my ($row, @pp); my @pieces = <p P n N b B r R q Q>; my @k = rand() < .5 ? <K k> : <k K>; for my $sq (0 .. 63) { if (any { $_ == $sq } @kings) { push @pp, shift @k; } elsif (any { $_ == $sq } @n) { $row = 7 - int $sq / 8; push @pp, $row == 0 ? pick1(grep { $_ ne 'P' } @pieces) : $row == 7 ? pick1(grep { $_ ne 'P' } @pieces) : pick1(@pieces); } else { push @pp, ''; } } my @qq; my $iter = natatime 8, @pp; while (my $row = join '', $iter->()) { $row =~ s/(()\2*)/length($1)/eg; push @qq, $row; } return join('/', @qq) . ' w - - 0 1'; } say gen_FEN();
789Generate random chess position
2perl
x3yw8
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'', '', '', '', ''} var B = symbols{'', '', '', '', ''} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr", "rknrn", "rkrnn"} func (sym symbols) chess960(id int) string { var pos [8]rune q, r := id/4, id%4 pos[r*2+1] = sym.b q, r = q/4, q%4 pos[r*2] = sym.b q, r = q/6, q%6 for i := 0; ; i++ { if pos[i] != 0 { continue } if r == 0 { pos[i] = sym.q break } r-- } i := 0 for _, f := range krn[q] { for pos[i] != 0 { i++ } switch f { case 'k': pos[i] = sym.k case 'r': pos[i] = sym.r case 'n': pos[i] = sym.n } } return string(pos[:]) } func main() { fmt.Println(" ID Start position") for _, id := range []int{0, 518, 959} { fmt.Printf("%3d %s\n", id, A.chess960(id)) } fmt.Println("\nRandom") for i := 0; i < 5; i++ { fmt.Println(W.chess960(rand.Intn(960))) } }
790Generate Chess960 starting position
0go
h8ojq
(defn fix [pairs] (map second pairs)) (defn getvalid [pairs n] (filter (fn [p] (zero? (mod n (first p)))) (sort-by first pairs))) (defn gfizzbuzz [pairs numbers] (interpose "\n" (map (fn [n] (let [f (getvalid pairs n)] (if (empty? f) n (apply str (fix f))))) numbers)))
791General FizzBuzz
6clojure
gxx4f
import Data.List import qualified Data.Set as Set data Piece = K | Q | R | B | N deriving (Eq, Ord, Show) isChess960 :: [Piece] -> Bool isChess960 rank = (odd . sum $ findIndices (== B) rank) && king > rookA && king < rookB where Just king = findIndex (== K) rank [rookA, rookB] = findIndices (== R) rank main :: IO () main = mapM_ (putStrLn . concatMap show) . Set.toList . Set.fromList . filter isChess960 $ permutations [R,N,B,Q,K,B,N,R]
790Generate Chess960 starting position
8haskell
il2or
import random board = [[ for x in range(8)] for y in range(8)] piece_list = [, , , , ] def place_kings(brd): while True: rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7) diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)] if sum(diff_list) > 2 or set(diff_list) == set([0, 2]): brd[rank_white][file_white], brd[rank_black][file_black] = , break def populate_board(brd, wp, bp): for x in range(2): if x == 0: piece_amount = wp pieces = piece_list else: piece_amount = bp pieces = [s.lower() for s in piece_list] while piece_amount != 0: piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7) piece = random.choice(pieces) if brd[piece_rank][piece_file] == and pawn_on_promotion_square(piece, piece_rank) == False: brd[piece_rank][piece_file] = piece piece_amount -= 1 def fen_from_board(brd): fen = for x in brd: n = 0 for y in x: if y == : n += 1 else: if n != 0: fen += str(n) fen += y n = 0 if n != 0: fen += str(n) fen += if fen.count() < 7 else fen += return fen def pawn_on_promotion_square(pc, pr): if pc == and pr == 0: return True elif pc == and pr == 7: return True return False def start(): piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15) place_kings(board) populate_board(board, piece_amount_white, piece_amount_black) print(fen_from_board(board)) for x in board: print(x) start()
789Generate random chess position
3python
q6mxi
import java.util.Arrays; import java.util.Collections; import java.util.List; public class Chess960{ private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R'); public static List<Character> generateFirstRank(){ do{ Collections.shuffle(pieces); }while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", "")));
790Generate Chess960 starting position
9java
x36wy
(defn first-digit [n] (Integer/parseInt (subs (str n) 0 1))) (defn last-digit [n] (mod n 10)) (defn bookend-number [n] (+ (* 10 (first-digit n)) (last-digit n))) (defn is-gapful? [n] (and (>= n 100) (zero? (mod n (bookend-number n))))) (defn gapful-from [n] (filter is-gapful? (iterate inc n))) (defn gapful [] (gapful-from 1)) (defn gapfuls-in-range [start size] (take size (gapful-from start))) (defn report-range [[start size]] (doall (map println [(format "First%d gapful numbers >=%d:" size start) (gapfuls-in-range start size) ""]))) (doall (map report-range [ [1 30] [1000000 15] [1000000000 10] ]))
793Gapful numbers
6clojure
89y05
void swap_row(double *a, double *b, int r1, int r2, int n) { double tmp, *p1, *p2; int i; if (r1 == r2) return; for (i = 0; i < n; i++) { p1 = mat_elem(a, r1, i, n); p2 = mat_elem(a, r2, i, n); tmp = *p1, *p1 = *p2, *p2 = tmp; } tmp = b[r1], b[r1] = b[r2], b[r2] = tmp; } void gauss_eliminate(double *a, double *b, double *x, int n) { int i, j, col, row, max_row,dia; double max, tmp; for (dia = 0; dia < n; dia++) { max_row = dia, max = A(dia, dia); for (row = dia + 1; row < n; row++) if ((tmp = fabs(A(row, dia))) > max) max_row = row, max = tmp; swap_row(a, b, dia, max_row, n); for (row = dia + 1; row < n; row++) { tmp = A(row, dia) / A(dia, dia); for (col = dia+1; col < n; col++) A(row, col) -= tmp * A(dia, col); A(row, dia) = 0; b[row] -= tmp * b[dia]; } } for (row = n - 1; row >= 0; row--) { tmp = b[row]; for (j = n - 1; j > row; j--) tmp -= x[j] * A(row, j); x[row] = tmp / A(row, row); } } int main(void) { double a[] = { 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 }; double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 }; double x[6]; int i; gauss_eliminate(a, b, x, 6); for (i = 0; i < 6; i++) printf(, x[i]); return 0; }
794Gaussian elimination
5c
ck79c
place_kings <- function(brd){ while (TRUE) { rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1) rank_black <- sample(1:8, 1) ; file_black <- sample(1:8, 1) diff_vec <- c(abs(rank_white - rank_black), abs(file_white - file_black)) if (sum(diff_vec) > 2 | setequal(diff_vec, c(0,2))) { brd[rank_white, file_white] <- "K" brd[rank_black, file_black] <- "k" break } } return(brd) } pawn_on_extreme_ranks <- function(pc, pr){ if (pc %in% c("P","p") & pr %in% c(1,8)) return(TRUE) else return(FALSE) } populate_board <- function(brd, wp, bp){ piece_list <- c("P", "N", "B", "R", "Q") for (color in c("white", "black")){ if (color == "white"){ n_pieces = wp pieces = piece_list } else { n_pieces = bp pieces = tolower(piece_list) } while (n_pieces != 0){ piece_rank <- sample(1:8, 1) ; piece_file <- sample(1:8, 1) piece <- sample(pieces, 1) if (brd[piece_rank, piece_file] == " " & !pawn_on_extreme_ranks(piece, piece_rank)){ brd[piece_rank, piece_file] <- piece n_pieces <- n_pieces - 1 } } } return(brd) } fen_from_board <- function(brd){ fen <- apply(brd, 1, function(x) { r <- rle(x) paste(ifelse(r$values == " ", r$lengths, r$values), collapse = "") }) fen <- paste(paste(fen, collapse = "/"), "w - - 0 1") return(fen) } generate_fen <- function(){ board <- matrix(" ", nrow = 8, ncol = 8) n_pieces_white <- sample(0:31, 1) ; n_pieces_black <- sample(0:31, 1) board <- place_kings(board) board <- populate_board(board, wp = n_pieces_white, bp = n_pieces_black) print(board) cat("\n") cat(fen_from_board(board)) } generate_fen()
789Generate random chess position
13r
afz1z
package main import ( "fmt" "math" )
788Generator/Exponential
0go
4ws52
function gcd(a: number, b: number) { a = Math.abs(a); b = Math.abs(b); if (b > a) { let temp = a; a = b; b = temp; } while (true) { a %= b; if (a === 0) { return b; } b %= a; if (b === 0) { return a; } } }
787Greatest common divisor
20typescript
5esu4
function ch960startPos() { var rank = new Array(8),
790Generate Chess960 starting position
10javascript
ocl86
int noargs(void); int twoargs(int a,int b); int twoargs(int ,int); int anyargs(); int atleastoneargs(int, ...);
795Function prototype
5c
lb7cy
int main() { unsigned char lower[N]; for (size_t i = 0; i < N; i++) { lower[i] = i + 'a'; } return EXIT_SUCCESS; }
796Generate lower case ASCII alphabet
5c
z4ltx
import Data.List.Ordered powers :: Int -> [Int] powers m = map (^ m) [0..] squares :: [Int] squares = powers 2 cubes :: [Int] cubes = powers 3 foo :: [Int] foo = filter (not . has cubes) squares main :: IO () main = print $ take 10 $ drop 20 foo
788Generator/Exponential
8haskell
q69x9
object Chess960 : Iterable<String> { override fun iterator() = patterns.iterator() private operator fun invoke(b: String, e: String) { if (e.length <= 1) { val s = b + e if (s.is_valid()) patterns += s } else { for (i in 0 until e.length) { invoke(b + e[i], e.substring(0, i) + e.substring(i + 1)) } } } private fun String.is_valid(): Boolean { val k = indexOf('K') return indexOf('R') < k && k < lastIndexOf('R') && indexOf('B') % 2 != lastIndexOf('B') % 2 } private val patterns = sortedSetOf<String>() init { invoke("", "KQRRNNBB") } } fun main(args: Array<String>) { Chess960.forEachIndexed { i, s -> println("$i: $s") } }
790Generate Chess960 starting position
11kotlin
pndb6
(declare foo)
795Function prototype
6clojure
4wp5o
package main import "fmt" type vector = []float64 type matrix []vector func (m matrix) inverse() matrix { le := len(m) for _, v := range m { if len(v) != le { panic("Not a square matrix") } } aug := make(matrix, le) for i := 0; i < le; i++ { aug[i] = make(vector, 2*le) copy(aug[i], m[i])
792Gauss-Jordan matrix inversion
0go
6rg3p
null
790Generate Chess960 starting position
1lua
1dfpo
package main import "fmt" type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode } func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} } func (n *FCNode) addChildren(nodes []*FCNode) { for _, node := range nodes { node.parent = n n.children = append(n.children, node) } n.updateCoverage() } func (n *FCNode) setCoverage(value float64) { if n.coverage != value { n.coverage = value
797Functional coverage tree
0go
pnqbg
def hasNK( board, a, b ) for g in -1 .. 1 for f in -1 .. 1 aa = a + f; bb = b + g if aa.between?( 0, 7 ) && bb.between?( 0, 7 ) p = board[aa + 8 * bb] if p == || p == ; return true; end end end end return false end def generateBoard( board, pieces ) while( pieces.length > 1 ) p = pieces[pieces.length - 1] pieces = pieces[0...-1] while( true ) a = rand( 8 ); b = rand( 8 ) if ( ( b == 0 || b == 7 ) && ( p == || p == ) ) || ( ( p == || p == ) && hasNK( board, a, b ) ); next; end if board[a + b * 8] == nil; break;end end board[a + b * 8] = p end end pieces = for i in 0 .. 10 e = pieces.length - 1 while e > 0 p = rand( e ); t = pieces[e]; pieces[e] = pieces[p]; pieces[p] = t; e -= 1 end end board = Array.new( 64 ); generateBoard( board, pieces ) puts e = 0 for j in 0 .. 7 for i in 0 .. 7 if board[i + 8 * j] == nil; e += 1 else if e > 0; print( e ); e = 0; end print( board[i + 8 * j] ) end end if e > 0; print( e ); e = 0; end if j < 7; print( ); end end print( ) for j in 0 .. 7 for i in 0 .. 7 if board[i + j * 8] == nil; print( ) else print( board[i + j * 8] ); end end puts end
789Generate random chess position
14ruby
0mcsu
isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs isSquareMatrix xs = null xs || all ((== (length xs)).length) xs mult:: Num a => [[a]] -> [[a]] -> [[a]] mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss matI::(Num a) => Int -> [[a]] matI n = [ [fromIntegral.fromEnum $ i == j | j <- [1..n]] | i <- [1..n]] inversion xs = gauss xs (matI $ length xs) gauss::[[Double]] -> [[Double]] -> [[Double]] gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs) where toR = map $ map toRational solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]] solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = [] | otherwise = uncurry solveTriangle $ triangle xs bs solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]] solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = [] solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b] where val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) go [] _ zs = zs go _ [] zs = zs go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]]) triangle xs bs = triang ([],[]) (xs,bs) where triang ts (_,[]) = ts triang ts ([],_) = ts triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)] where ((us@(u:tus)):uss,cs:css) = bubble zs bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]]) bubble (xs,bs) = (go xs, go bs) where idmax = snd.maximum.flip zip [0..].map (abs.head) $ xs go ys = let (us,vs) = splitAt idmax ys in vs ++ us main = do let a = [[1, 2, 3], [4, 1, 6], [7, 8, 9]] let b = [[2, -1, 0], [-1, 2, -1], [0, -1, 2]] putStrLn "inversion a =" mapM_ print $ inversion a putStrLn "\ninversion b =" mapM_ print $ inversion b
792Gauss-Jordan matrix inversion
8haskell
j0s7g
(map char (range (int \a) (inc (int \z))))
796Generate lower case ASCII alphabet
6clojure
9h4ma
import Data.Bifunctor (first) import Data.Bool (bool) import Data.Char (isSpace) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Read as T import Data.Tree (Forest, Tree (..), foldTree) import Numeric (showFFloat) import System.Directory (doesFileExist) data Coverage = Coverage { name :: T.Text, weight :: Float, coverage :: Float, share :: Float } deriving (Show) fp = "./coverageOutline.txt" main :: IO () main = doesFileExist fp >>= bool (print $ "File not found: " <> fp) (T.readFile fp >>= T.putStrLn . updatedCoverageOutline) updatedCoverageOutline :: T.Text -> T.Text updatedCoverageOutline s = let delimiter = "|" indentedLines = T.lines s columnNames = init $ tokenizeWith delimiter ( head indentedLines ) in T.unlines [ tabulation delimiter (columnNames <> ["SHARE OF RESIDUE"]), indentedLinesFromTree " " (showCoverage delimiter) $ withResidueShares 1.0 $ foldTree weightedCoverage (parseTreeFromOutline delimiter indentedLines) ] weightedCoverage :: Coverage -> Forest Coverage -> Tree Coverage weightedCoverage x xs = let cws = ((,) . coverage <*> weight) . rootLabel <$> xs totalWeight = foldr ((+) . snd) 0 cws in Node ( x { coverage = foldr (\(c, w) a -> (c * w) + a) (coverage x) cws / bool 1 totalWeight (0 < totalWeight) } ) xs withResidueShares :: Float -> Tree Coverage -> Tree Coverage withResidueShares shareOfTotal tree = let go fraction node = let forest = subForest node weights = weight . rootLabel <$> forest weightTotal = sum weights nodeRoot = rootLabel node in Node ( nodeRoot { share = fraction * (1 - coverage nodeRoot) } ) ( zipWith go ((fraction *) . (/ weightTotal) <$> weights) forest ) in go shareOfTotal tree parseTreeFromOutline :: T.Text -> [T.Text] -> Tree Coverage parseTreeFromOutline delimiter indentedLines = partialRecord . tokenizeWith delimiter <$> head ( forestFromLineIndents $ indentLevelsFromLines $ tail indentedLines ) forestFromLineIndents :: [(Int, T.Text)] -> [Tree T.Text] forestFromLineIndents pairs = let go [] = [] go ((n, s): xs) = let (firstTreeLines, rest) = span ((n <) . fst) xs in Node s (go firstTreeLines): go rest in go pairs indentLevelsFromLines :: [T.Text] -> [(Int, T.Text)] indentLevelsFromLines xs = let pairs = T.span isSpace <$> xs indentUnit = foldr ( \x a -> let w = (T.length . fst) x in bool a w (w < a && 0 < w) ) (maxBound :: Int) pairs in first (flip div indentUnit . T.length) <$> pairs partialRecord :: [T.Text] -> Coverage partialRecord xs = let [name, weightText, coverageText] = take 3 (xs <> repeat "") in Coverage { name = name, weight = defaultOrRead 1.0 weightText, coverage = defaultOrRead 0.0 coverageText, share = 0.0 } defaultOrRead :: Float -> T.Text -> Float defaultOrRead n txt = either (const n) fst $ T.rational txt tokenizeWith :: T.Text -> T.Text -> [T.Text] tokenizeWith delimiter = fmap T.strip . T.splitOn delimiter indentedLinesFromTree :: T.Text -> (T.Text -> a -> T.Text) -> Tree a -> T.Text indentedLinesFromTree tab showRoot tree = let go indent node = showRoot indent (rootLabel node): (subForest node >>= go (T.append tab indent)) in T.unlines $ go "" tree showCoverage :: T.Text -> T.Text -> Coverage -> T.Text showCoverage delimiter indent x = tabulation delimiter ( [T.append indent (name x), T.pack (showN 0 (weight x))] <> (T.pack . showN 4 <$> ([coverage, share] <*> [x])) ) tabulation :: T.Text -> [T.Text] -> T.Text tabulation delimiter = T.intercalate (T.append delimiter " ") . zipWith (`T.justifyLeft` ' ') [31, 9, 9, 9] justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = (drop . length) <*> (replicate n c <>) showN :: Int -> Float -> String showN p n = justifyRight 7 ' ' (showFFloat (Just p) n "")
797Functional coverage tree
8haskell
fumd1
int n, w, h = 45, *x, *y, cnt = 0; char *b; inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; } void show_board() { int i, j; for (puts(), i = 0; i < h; i++, putchar('\n')) for (j = 0; j < w; j++, putchar(' ')) printf(B(i, j) == '*' ? C(i - 1, j) ? : : , B(i, j)); } void init() { int i, j; puts(); b = malloc(w * h); memset(b, ' ', w * h); x = malloc(sizeof(int) * BALLS * 2); y = x + BALLS; for (i = 0; i < n; i++) for (j = -i; j <= i; j += 2) B(2 * i+2, j + w/2) = '*'; srand(time(0)); } void move(int idx) { int xx = x[idx], yy = y[idx], c, kill = 0, sl = 3, o = 0; if (yy < 0) return; if (yy == h - 1) { y[idx] = -1; return; } switch(c = B(yy + 1, xx)) { case ' ': yy++; break; case '*': sl = 1; default: if (xx < w - 1 && C(yy, xx + 1) && C(yy + 1, xx + 1)) if (!rnd(sl++)) o = 1; if (xx && C(yy, xx - 1) && C(yy + 1, xx - 1)) if (!rnd(sl++)) o = -1; if (!o) kill = 1; xx += o; } c = V(idx); V(idx) = ' '; idx[y] = yy, idx[x] = xx; B(yy, xx) = c; if (kill) idx[y] = -1; } int run(void) { static int step = 0; int i; for (i = 0; i < cnt; i++) move(i); if (2 == ++step && cnt < BALLS) { step = 0; x[cnt] = w/2; y[cnt] = 0; if (V(cnt) != ' ') return 0; V(cnt) = rnd(80) + 43; cnt++; } return 1; } int main(int c, char **v) { if (c < 2 || (n = atoi(v[1])) <= 3) n = 5; if (n >= 20) n = 20; w = n * 2 + 1; init(); do { show_board(), usleep(60000); } while (run()); return 0; }
798Galton box animation
5c
lb4cy
use std::fmt::Write; use rand::{Rng, distributions::{Distribution, Standard}}; const EMPTY: u8 = b'.'; #[derive(Clone, Debug)] struct Board { grid: [[u8; 8]; 8], } impl Distribution<Board> for Standard { fn sample<R: Rng +?Sized>(&self, rng: &mut R) -> Board { let mut board = Board::empty(); board.place_kings(rng); board.place_pieces(rng, b"PPPPPPPP", true); board.place_pieces(rng, b"pppppppp", true); board.place_pieces(rng, b"RNBQBNR", false); board.place_pieces(rng, b"rnbqbnr", false); board } } impl Board { fn empty() -> Self { Board { grid: [[EMPTY; 8]; 8] } } fn fen(&self) -> String { let mut fen = String::new(); let mut count_empty = 0; for row in &self.grid { for &ch in row { print!("{} ", ch as char); if ch == EMPTY { count_empty += 1; } else { if count_empty > 0 { write!(fen, "{}", count_empty).unwrap(); count_empty = 0; } fen.push(ch as char); } } if count_empty > 0 { write!(fen, "{}", count_empty).unwrap(); count_empty = 0; } fen.push('/'); println!(); } fen.push_str(" w - - 0 1"); fen } fn place_kings<R: Rng +?Sized>(&mut self, rng: &mut R) { loop { let r1: i8 = rng.gen_range(0, 8); let c1: i8 = rng.gen_range(0, 8); let r2: i8 = rng.gen_range(0, 8); let c2: i8 = rng.gen_range(0, 8); if r1!= r2 && (r1 - r2).abs() > 1 && (c1 - c2).abs() > 1 { self.grid[r1 as usize][c1 as usize] = b'K'; self.grid[r2 as usize][c2 as usize] = b'k'; return; } } } fn place_pieces<R: Rng +?Sized>(&mut self, rng: &mut R, pieces: &[u8], is_pawn: bool) { let num_to_place = rng.gen_range(0, pieces.len()); for &piece in pieces.iter().take(num_to_place) { let mut r = rng.gen_range(0, 8); let mut c = rng.gen_range(0, 8); while self.grid[r][c]!= EMPTY || (is_pawn && (r == 7 || r == 0)) { r = rng.gen_range(0, 8); c = rng.gen_range(0, 8); } self.grid[r][c] = piece; } } } fn main() { let b: Board = rand::random(); println!("{}", b.fen()); }
789Generate random chess position
15rust
89l07
import scala.math.abs import scala.util.Random object RandomFen extends App { val rand = new Random private def createFen = { val grid = Array.ofDim[Char](8, 8) def placeKings(grid: Array[Array[Char]]): Unit = { var r1, c1, r2, c2 = 0 do { r1 = rand.nextInt(8) c1 = rand.nextInt(8) r2 = rand.nextInt(8) c2 = rand.nextInt(8) } while (r1 == r2 || abs(r1 - r2) <= 1 || abs(c1 - c2) <= 1) grid(r1)(c1) = 'K' grid(r2)(c2) = 'k' } def placePieces(grid: Array[Array[Char]], pieces: String, isPawn: Boolean): Unit = { val numToPlace = rand.nextInt(pieces.length) for (n <- 0 until numToPlace) { var r, c = 0 do { r = rand.nextInt(8) c = rand.nextInt(8) } while (grid(r)(c) != 0 || (isPawn && (r == 7 || r == 0))) grid(r)(c) = pieces(n) } } def toFen(grid: Array[Array[Char]]) = { val fen = new StringBuilder var countEmpty = 0 for (r <- grid.indices) { for (c <- grid.indices) { val ch = grid(r)(c) print(f"${if (ch == 0) '.' else ch}%2c ") if (ch == 0) countEmpty += 1 else { if (countEmpty > 0) { fen.append(countEmpty) countEmpty = 0 } fen.append(ch) } } if (countEmpty > 0) { fen.append(countEmpty) countEmpty = 0 } fen.append("/") println() } fen.append(" w - - 0 1").toString } placeKings(grid) placePieces(grid, "PPPPPPPP", isPawn = true) placePieces(grid, "pppppppp", isPawn = true) placePieces(grid, "RNBQBNR", isPawn = false) placePieces(grid, "rnbqbnr", isPawn = false) toFen(grid) } println(createFen) }
789Generate random chess position
16scala
n2uic
import java.util.function.LongSupplier; import static java.util.stream.LongStream.generate; public class GeneratorExponential implements LongSupplier { private LongSupplier source, filter; private long s, f; public GeneratorExponential(LongSupplier source, LongSupplier filter) { this.source = source; this.filter = filter; f = filter.getAsLong(); } @Override public long getAsLong() { s = source.getAsLong(); while (s == f) { s = source.getAsLong(); f = filter.getAsLong(); } while (s > f) { f = filter.getAsLong(); } return s; } public static void main(String[] args) { generate(new GeneratorExponential(new SquaresGen(), new CubesGen())) .skip(20).limit(10) .forEach(n -> System.out.printf("%d ", n)); } } class SquaresGen implements LongSupplier { private long n; @Override public long getAsLong() { return n * n++; } } class CubesGen implements LongSupplier { private long n; @Override public long getAsLong() { return n * n * n++; } }
788Generator/Exponential
9java
pntb3
(() => { 'use strict';
797Functional coverage tree
10javascript
dvynu
class Fen { public createFen() { let grid: string[][]; grid = []; for (let r = 0; r < 8; r++) { grid[r] = []; for (let c = 0; c < 8; c++) { grid[r][c] = "0"; } } this.placeKings(grid); this.placePieces(grid, "PPPPPPPP", true); this.placePieces(grid, "pppppppp", true); this.placePieces(grid, "RNBQBNR", false); this.placePieces(grid, "rnbqbnr", false); return this.toFen(grid); } private placeKings(grid: string[][]): void { let r1, c1, r2, c2: number; while (true) { r1 = Math.floor(Math.random() * 8); c1 = Math.floor(Math.random() * 8); r2 = Math.floor(Math.random() * 8); c2 = Math.floor(Math.random() * 8); if (r1!= r2 && Math.abs(r1 - r2) > 1 && Math.abs(c1 - c2) > 1) { break; } } grid[r1][c1] = "K"; grid[r2][c2] = "k"; } private placePieces(grid: string[][], pieces: string, isPawn: boolean): void { let numToPlace: number = Math.floor(Math.random() * pieces.length); for (let n = 0; n < numToPlace; n++) { let r, c: number; do { r = Math.floor(Math.random() * 8); c = Math.floor(Math.random() * 8); } while (grid[r][c]!= "0" || (isPawn && (r == 7 || r == 0))); grid[r][c] = pieces.charAt(n); } } private toFen(grid: string[][]): string { let result: string = ""; let countEmpty: number = 0; for (let r = 0; r < 8; r++) { for (let c = 0; c < 8; c++) { let char: string = grid[r][c]; if (char == "0") { countEmpty++; } else { if (countEmpty > 0) { result += countEmpty; countEmpty = 0; } result += char; } } if (countEmpty > 0) { result += countEmpty; countEmpty = 0; } result += "/"; } return result += " w - - 0 1"; } } let fen: Fen = new Fen(); console.log(fen.createFen());
789Generate random chess position
20typescript
9hbmb
null
792Gauss-Jordan matrix inversion
9java
ua1vv
package main import ( "fmt" ) const numbers = 3 func main() {
791General FizzBuzz
0go
q66xz
function PowersGenerator(m) { var n=0; while(1) { yield Math.pow(n, m); n += 1; } } function FilteredGenerator(g, f){ var value = g.next(); var filter = f.next(); while(1) { if( value < filter ) { yield value; value = g.next(); } else if ( value > filter ) { filter = f.next(); } else { value = g.next(); filter = f.next(); } } } var squares = PowersGenerator(2); var cubes = PowersGenerator(3); var filtered = FilteredGenerator(squares, cubes); for( var x = 0; x < 20; x++ ) filtered.next() for( var x = 20; x < 30; x++ ) console.logfiltered.next());
788Generator/Exponential
10javascript
x3mw9
null
797Functional coverage tree
11kotlin
et8a4
struct functionInfo { char* name; int timesCalled; char marked; }; void addToList(struct functionInfo** list, struct functionInfo toAdd, \ size_t* numElements, size_t* allocatedSize) { static const char* keywords[32] = {, , , , , \ , , , , \ , , , , , \ , , , , , \ , , , , \ , , , , \ , , , , \ }; int i; for (i = 0; i < 32; i++) { if (!strcmp(toAdd.name, keywords[i])) { return; } } if (!*list) { *allocatedSize = 10; *list = calloc(*allocatedSize, sizeof(struct functionInfo)); if (!*list) { printf(, \ *allocatedSize, sizeof(struct functionInfo)); abort(); } (*list)[0].name = malloc(strlen(toAdd.name)+1); if (!(*list)[0].name) { printf(, strlen(toAdd.name)+1); abort(); } strcpy((*list)[0].name, toAdd.name); (*list)[0].timesCalled = 1; (*list)[0].marked = 0; *numElements = 1; } else { char found = 0; unsigned int i; for (i = 0; i < *numElements; i++) { if (!strcmp((*list)[i].name, toAdd.name)) { found = 1; (*list)[i].timesCalled++; break; } } if (!found) { struct functionInfo* newList = calloc((*allocatedSize)+10, \ sizeof(struct functionInfo)); if (!newList) { printf(, \ (*allocatedSize)+10, sizeof(struct functionInfo)); abort(); } memcpy(newList, *list, (*allocatedSize)*sizeof(struct functionInfo)); free(*list); *allocatedSize += 10; *list = newList; (*list)[*numElements].name = malloc(strlen(toAdd.name)+1); if (!(*list)[*numElements].name) { printf(, strlen(toAdd.name)+1); abort(); } strcpy((*list)[*numElements].name, toAdd.name); (*list)[*numElements].timesCalled = 1; (*list)[*numElements].marked = 0; (*numElements)++; } } } void printList(struct functionInfo** list, size_t numElements) { char maxSet = 0; unsigned int i; size_t maxIndex = 0; for (i = 0; i<10; i++) { maxSet = 0; size_t j; for (j = 0; j<numElements; j++) { if (!maxSet || (*list)[j].timesCalled > (*list)[maxIndex].timesCalled) { if (!(*list)[j].marked) { maxSet = 1; maxIndex = j; } } } (*list)[maxIndex].marked = 1; printf(, (*list)[maxIndex].name, \ (*list)[maxIndex].timesCalled); } } void freeList(struct functionInfo** list, size_t numElements) { size_t i; for (i = 0; i<numElements; i++) { free((*list)[i].name); } free(*list); } char* extractFunctionName(char* readHead) { char* identifier = readHead; if (isalpha(*identifier) || *identifier == '_') { while (isalnum(*identifier) || *identifier == '_') { identifier++; } } char* toParen = identifier; if (toParen == readHead) return NULL; while (isspace(*toParen)) { toParen++; } if (*toParen != '(') return NULL; ptrdiff_t size = (ptrdiff_t)((ptrdiff_t)identifier) \ - ((ptrdiff_t)readHead)+1; char* const name = malloc(size); if (!name) { printf(, size); abort(); } name[size-1] = '\0'; memcpy(name, readHead, size-1); if (strcmp(name, )) { return name; } free(name); return NULL; } int main(int argc, char** argv) { int i; for (i = 1; i<argc; i++) { errno = 0; FILE* file = fopen(argv[i], ); if (errno || !file) { printf(%s\, \ strerror(errno)); abort(); } char comment = 0; int string = 0; struct functionInfo* functions = NULL; struct functionInfo toAdd; size_t numElements = 0; size_t allocatedSize = 0; struct stat metaData; errno = 0; if (fstat(fileno(file), &metaData) < 0) { printf(%s\, strerror(errno)); abort(); } char* mmappedSource = (char*)mmap(NULL, metaData.st_size, PROT_READ, \ MAP_PRIVATE, fileno(file), 0); if (errno) { printf(%s\, strerror(errno)); abort(); } if (!mmappedSource) { printf(); abort(); } char* readHead = mmappedSource; while (readHead < mmappedSource + metaData.st_size) { while (*readHead) { if (!string) { if (*readHead == '/' && !strncmp(readHead, , 2)) { comment = 1; } if (*readHead == '*' && !strncmp(readHead, , 2)) { comment = 0; } } if (!comment) { if (*readHead == '\\\, 2)) { string = 0; } } } if (*readHead == '\'') { if (!string) { string = SINGLEQUOTE; } else if (string == SINGLEQUOTE) { if (strncmp((readHead-1), , 2)) { string = 0; } } } } if (!comment && !string) { char* name = extractFunctionName(readHead); if (name) { toAdd.name = name; addToList(&functions, toAdd, &numElements, &allocatedSize); readHead += strlen(name); } free(name); } readHead++; } } errno = 0; munmap(mmappedSource, metaData.st_size); if (errno) { printf(%s\, strerror(errno)); abort(); } errno = 0; fclose(file); if (errno) { printf(%s\, strerror(errno)); abort(); } printList(&functions, numElements); freeList(&functions, numElements); } return 0; }
799Function frequency
5c
7sbrg
def log = '' (1..40).each {Integer value -> log +=(value %3 == 0) ? (value %5 == 0)? 'FIZZBUZZ\n':(value %7 == 0)? 'FIZZBAXX\n':'FIZZ\n' :(value %5 == 0) ? (value %7 == 0)? 'BUZBAXX\n':'BUZZ\n' :(value %7 == 0) ?'BAXX\n' :(value+'\n')} println log
791General FizzBuzz
7groovy
1ddp6
sub rnd($) { int(rand(shift)) } sub empties { grep !$_[0][$_], 0 .. 7 } sub chess960 { my @s = (undef) x 8; @s[2*rnd(4), 1 + 2*rnd(4)] = qw/B B/; for (qw/Q N N/) { my @idx = empties \@s; $s[$idx[rnd(@idx)]] = $_; } @s[empties \@s] = qw/R K R/; @s } print "@{[chess960]}\n" for 0 .. 10;
790Generate Chess960 starting position
2perl
y7j6u
func a()
795Function prototype
0go
x3dwf