code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
= 1 += 1 puts
87Unicode variable names
14ruby
hgdjx
#![feature(non_ascii_idents)] #![allow(non_snake_case)] fn main() { let mut : i32 = 1; += 1; println!("{}", ); }
87Unicode variable names
15rust
krfh5
public class Bias { public static boolean biased(int n) { return Math.random() < 1.0 / n; } public static boolean unbiased(int n) { boolean a, b; do { a = biased(n); b = biased(n); } while (a == b); return a; } public static void main(String[] args) { final int M = 50000; for (int n = 3; n < 7; n++) { int c1 = 0, c2 = 0; for (int i = 0; i < M; i++) { c1 += biased(n) ? 1 : 0; c2 += unbiased(n) ? 1 : 0; } System.out.format("%d:%2.2f%% %2.2f%%\n", n, 100.0*c1/M, 100.0*c2/M); } } }
90Unbias a random generator
9java
akt1y
import Foundation infix operator : MultiplicationPrecedence infix operator : MultiplicationPrecedence public struct Vector { public var x = 0.0 public var y = 0.0 public var z = 0.0 public init(x: Double, y: Double, z: Double) { (self.x, self.y, self.z) = (x, y, z) } public static func (lhs: Vector, rhs: Vector) -> Double { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z } public static func (lhs: Vector, rhs: Vector) -> Vector { return Vector( x: lhs.y * rhs.z - lhs.z * rhs.y, y: lhs.z * rhs.x - lhs.x * rhs.z, z: lhs.x * rhs.y - lhs.y * rhs.x ) } } let a = Vector(x: 3, y: 4, z: 5) let b = Vector(x: 4, y: 3, z: 5) let c = Vector(x: -5, y: -12, z: -13) print("a: \(a)") print("b: \(b)") print("c: \(c)") print() print("a b = \(a b)") print("a b = \(a b)") print("a (b c) = \(a (b c))") print("a (b c) = \(a (b c))")
72Vector products
17swift
qa1xg
puts unless defined? var var = puts unless defined? var puts
85Undefined values
14ruby
uc0vz
use std::ptr; let p: *const i32 = ptr::null(); assert!(p.is_null());
85Undefined values
15rust
5l8uq
var = 1 val = 3.141592 val = "hello" += 1 println()
87Unicode variable names
16scala
1h3pf
null
90Unbias a random generator
11kotlin
hgoj3
import numpy as np class Revolver: def __init__(self): self.cylinder = np.array([False] * 6) def unload(self): self.cylinder[:] = False def load(self): while self.cylinder[1]: self.cylinder[:] = np.roll(self.cylinder, 1) self.cylinder[1] = True def spin(self): self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7)) def fire(self): shot = self.cylinder[0] self.cylinder[:] = np.roll(self.cylinder, 1) return shot def LSLSFSF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LSLSFF(self): self.unload() self.load() self.spin() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False def LLSFSF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True self.spin() if self.fire(): return True return False def LLSFF(self): self.unload() self.load() self.load() self.spin() if self.fire(): return True if self.fire(): return True return False if __name__ == '__main__': REV = Revolver() TESTCOUNT = 100000 for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF], ['load, spin, load, spin, fire, fire', REV.LSLSFF], ['load, load, spin, fire, spin, fire', REV.LLSFSF], ['load, load, spin, fire, fire', REV.LLSFF]]: percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT print(, name, , percentage, )
94Two bullet roulette
3python
ruegq
var x; # declared, but not defined x == nil && say "nil value"; defined(x) || say "undefined"; # Give "x" some value x = 42; defined(x) && say "defined"; # Change "x" back to `nil` x = nil; defined(x) || say "undefined";
85Undefined values
16scala
rungn
str = str.include?()
92Unicode strings
14ruby
8xm01
object UTF8 extends App { def charToInt(s: String) = { def charToInt0(c: Char, next: Char): Option[Int] = (c, next) match { case _ if (c.isHighSurrogate && next.isLowSurrogate) => Some(java.lang.Character.toCodePoint(c, next)) case _ if (c.isLowSurrogate) => None case _ => Some(c.toInt) } if (s.length > 1) charToInt0(s(0), s(1)) else Some(s.toInt) } def intToChars(n: Int) = java.lang.Character.toChars(n).mkString println('\uD869'.isHighSurrogate + " " + '\uDEA5'.isLowSurrogate) println(charToInt("\uD869\uDEA5")) val b = "\uD869\uDEA5" println(b) val c = "\uD834\uDD1E" println(c) val a = "$abcde". map(c => "%s\t\\u%04X".format(c, c.toInt)).foreach(println) }
92Unicode strings
16scala
d82ng
package main import "fmt" func sieve(limit uint64) []bool { limit++
95Twin primes
0go
ebia6
var = 1 let = 3.141592 let = "hello" ++ println()
87Unicode variable names
17swift
j4n74
local function randN(n) return function() if math.random() < 1/n then return 1 else return 0 end end end local function unbiased(n) local biased = randN (n) return function() local a, b = biased(), biased() while a==b do a, b = biased(), biased() end return a end end local function demonstrate (samples) for n = 3, 6 do biased = randN(n) unbias = unbiased(n) local bcounts = {[0]=0,[1]=0} local ucounts = {[0]=0,[1]=0} for i=1, samples do local bnum = biased() local unum = unbias() bcounts[bnum] = bcounts[bnum]+1 ucounts[unum] = ucounts[unum]+1 end print(string.format("N =%d",n), "# 0", "# 1", "% 0", "% 1") print("biased", bcounts[0], bcounts[1], bcounts[0] / samples * 100, bcounts[1] / samples * 100) print("unbias", ucounts[0], ucounts[1], ucounts[0] / samples * 100, ucounts[1] / samples * 100) end end demonstrate(100000)
90Unbias a random generator
1lua
krih2
void oops(const wchar_t *message) { wchar_t *buf; DWORD error; buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL); if (buf) { fwprintf(stderr, L, message, buf); LocalFree(buf); } else { fwprintf(stderr, L, message, error); } } int dotruncate(wchar_t *fn, LARGE_INTEGER fp) { HANDLE fh; fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(fn); return 1; } if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 || SetEndOfFile(fh) == 0) { oops(fn); CloseHandle(fh); return 1; } CloseHandle(fh); return 0; } int main() { LARGE_INTEGER fp; int argc; wchar_t **argv, *fn, junk[2]; argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L); return 1; } if (argc != 3) { fwprintf(stderr, L, argv[0]); return 1; } fn = argv[1]; if (swscanf(argv[2], L, &fp.QuadPart, &junk) != 1) { fwprintf(stderr, L, argv[2]); return 1; } return dotruncate(fn, fp); }
96Truncate a file
5c
mz5ys
typedef uint32_t bitsieve; unsigned sieve_check(bitsieve *b, const unsigned v) { if ((v != 2 && !(v & 1)) || (v < 2)) return 0; else return !(b[v >> 6] & (1 << (v >> 1 & 31))); } bitsieve* sieve(const unsigned v) { unsigned i, j; bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t)); for (i = 3; i <= sqrt(v); i += 2) if (!(b[i >> 6] & (1 << (i >> 1 & 31)))) for (j = i*i; j < v; j += (i << 1)) b[j >> 6] |= (1 << (j >> 1 & 31)); return b; } int ulam_get_map(int x, int y, int n) { x -= (n - 1) / 2; y -= n / 2; int mx = abs(x), my = abs(y); int l = 2 * max(mx, my); int d = y >= x ? l * 3 + x + y : l - x - y; return pow(l - 1, 2) + d; } void output_ulam_spiral(int n, const char glyph) { n -= n % 2 == 0 ? 1 : 0; const char *spaces = ; int mwidth = log10(n * n) + 1; bitsieve *b = sieve(n * n + 1); int x, y; for (x = 0; x < n; ++x) { for (y = 0; y < n; ++y) { int z = ulam_get_map(y, x, n); if (glyph == 0) { if (sieve_check(b, z)) printf(, mwidth, z); else printf(, mwidth, spaces); } else { printf(, sieve_check(b, z) ? glyph : spaces[0]); } } printf(); } free(b); } int main(int argc, char *argv[]) { const int n = argc < 2 ? 9 : atoi(argv[1]); output_ulam_spiral(n, 0); printf(); output_ulam_spiral(n, ' printf(); return 0; }
97Ulam spiral (for primes)
5c
42k5t
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
86Unix/ls
3python
ruigq
cat(paste(list.files(), collapse = "\n"), "\n") cat(paste(list.files("bar"), collapse = "\n"), "\n")
86Unix/ls
13r
ucsvx
let flag = "" print(flag.characters.count)
92Unicode strings
17swift
0wys6
# International class; name and street class ( , Strae ) { # Say who am I! method { say "I am #{self.} from #{self.Strae}"; } } # all the people of the world! var = [ ( "Friederich", "" ), ( "Smith ", "Cant" ), ( "Stanisaw Lec", "poudniow" ), ]; .each { |garon| garon.; }
92Unicode strings
15rust
oq983
import java.math.BigInteger; import java.util.Scanner; public class twinPrimes { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Search Size: "); BigInteger max = input.nextBigInteger(); int counter = 0; for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){ BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE); if(x.add(BigInteger.TWO).compareTo(max) <= 0) { counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0; } } System.out.println(counter + " twin prime pairs."); } public static boolean findPrime(BigInteger x, BigInteger sqrtNum){ for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){ if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){ return false; } } return true; } }
95Twin primes
9java
isyos
use strict; use warnings; use feature 'say'; use ntheory 'is_prime'; use enum qw(False True); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub is_unprimeable { my($n) = @_; return False if is_prime($n); my $chrs = length $n; for my $place (0..$chrs-1) { my $pow = 10**($chrs - $place - 1); my $this = substr($n, $place, 1) * $pow; map { return False if $this != $_ and is_prime($n - $this + $_ * $pow) } 0..9; } True } my($n, @ups); do { push @ups, $n if is_unprimeable(++$n); } until @ups == 600; say "First 35 unprimeables:\n" . join ' ', @ups[0..34]; printf "\n600th unprimeable:%s\n", comma $ups[599]; map { my $x = $_; while ($x += 10) { last if is_unprimeable($x) } say "First unprimeable that ends with $_: " . sprintf "%9s", comma $x; } 0..9;
88Unprimeable numbers
2perl
hgnjl
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size))) (truncate "truncate_test.txt" 2)
96Truncate a file
6clojure
v9j2f
Dir.foreach(){|n| puts n}
86Unix/ls
14ruby
j4d7x
use std::{env, fmt, fs, process}; use std::io::{self, Write}; use std::path::Path; fn main() { let cur = env::current_dir().unwrap_or_else(|e| exit_err(e, 1)); let arg = env::args().nth(1); print_files(arg.as_ref().map_or(cur.as_path(), |p| Path::new(p))) .unwrap_or_else(|e| exit_err(e, 2)); } #[inline] fn print_files(path: &Path) -> io::Result<()> { for x in try!(fs::read_dir(path)) { println!("{}", try!(x).file_name().to_string_lossy()); } Ok(()) } #[inline] fn exit_err<T>(msg: T, code: i32) ->! where T: fmt::Display { writeln!(&mut io::stderr(), "{}", msg).expect("Could not write to stderr"); process::exit(code) }
86Unix/ls
15rust
hgfj2
import java.math.BigInteger import java.util.* fun main() { val input = Scanner(System.`in`) println("Search Size: ") val max = input.nextBigInteger() var counter = 0 var x = BigInteger("3") while (x <= max) { val sqrtNum = x.sqrt().add(BigInteger.ONE) if (x.add(BigInteger.TWO) <= max) { counter += if (findPrime( x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE) ) && findPrime(x, sqrtNum) ) 1 else 0 } x = x.add(BigInteger.ONE) } println("$counter twin prime pairs.") } fun findPrime(x: BigInteger, sqrtNum: BigInteger?): Boolean { var divisor = BigInteger.TWO while (divisor <= sqrtNum) { if (x.remainder(divisor).compareTo(BigInteger.ZERO) == 0) { return false } divisor = divisor.add(BigInteger.ONE) } return true }
95Twin primes
11kotlin
qafx1
sub randn { my $n = shift; return int(rand($n) / ($n - 1)); } for my $n (3 .. 6) { print "Bias $n: "; my (@raw, @fixed); for (1 .. 10000) { my $x = randn($n); $raw[$x]++; $fixed[$x]++ if randn($n) != $x } print "@raw, "; printf("%3g+-%.3g%%\tfixed: ", $raw[0]/100, 100 * sqrt($raw[0] * $raw[1]) / ($raw[0] + $raw[1])**1.5); print "@fixed, "; printf("%3g+-%.3g%%\n", 100*$fixed[0]/($fixed[0] + $fixed[1]), 100 * sqrt($fixed[0] * $fixed[1]) / ($fixed[0] + $fixed[1])**1.5); }
90Unbias a random generator
2perl
zngtb
scala> new java.io.File("/").listFiles.sorted.foreach(println) /bin /boot /core /dev /etc /home /lib /lib64 /local /lost+found /media /mnt /opt /proc /root /run /sbin /selinux /srv /sys /tmp /user /usr /var
86Unix/ls
16scala
pj3bj
use strict; use warnings; use Primesieve; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } printf "Twin prime pairs less than%14s:%s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..10;
95Twin primes
2perl
v9h20
from itertools import count, islice def primes(_cache=[2, 3]): yield from _cache for n in count(_cache[-1]+2, 2): if isprime(n): _cache.append(n) yield n def isprime(n, _seen={0: False, 1: False}): def _isprime(n): for p in primes(): if p*p > n: return True if n%p == 0: return False if n not in _seen: _seen[n] = _isprime(n) return _seen[n] def unprime(): for a in count(1): d = 1 while d <= a: base = (a if any(isprime(y) for y in range(base, base + d*10, d)): break d *= 10 else: yield a print('First 35:') print(' '.join(str(i) for i in islice(unprime(), 35))) print('\nThe 600-th:') print(list(islice(unprime(), 599, 600))[0]) print() first, need = [False]*10, 10 for p in unprime(): i = p%10 if first[i]: continue first[i] = p need -= 1 if not need: break for i,v in enumerate(first): print(f'{i} ending: {v}')
88Unprimeable numbers
3python
krdhf
primes = [2, 3, 5, 7, 11, 13, 17, 19] def count_twin_primes(limit: int) -> int: global primes if limit > primes[-1]: ram_limit = primes[-1] + 90000000 - len(primes) reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1 while reasonable_limit < limit: ram_limit = primes[-1] + 90000000 - len(primes) if ram_limit > primes[-1]: reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) else: reasonable_limit = min(limit, primes[-1] ** 2) sieve = list({x for prime in primes for x in range(primes[-1] + prime - (primes[-1]% prime), reasonable_limit, prime)}) primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit] count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y]) return count def test(limit: int): count = count_twin_primes(limit) print(f) test(10) test(100) test(1000) test(10000) test(100000) test(1000000) test(10000000) test(100000000)
95Twin primes
3python
uckvd
import ( "fmt" "os" ) if err := os.Truncate("filename", newSize); err != nil { fmt.Println(err) }
96Truncate a file
0go
ak81f
typedef int bool; typedef struct { char name; bool val; } var; typedef struct { int top; bool els[STACK_SIZE]; } stack_of_bool; char expr[BUFFER_SIZE]; int expr_len; var vars[24]; int vars_len; bool is_full(stack_of_bool *sp) { return sp->top == STACK_SIZE - 1; } bool is_empty(stack_of_bool *sp) { return sp->top == -1; } bool peek(stack_of_bool *sp) { if (!is_empty(sp)) return sp->els[sp->top]; else { printf(); exit(1); } } void push(stack_of_bool *sp, bool val) { if (!is_full(sp)) { sp->els[++(sp->top)] = val; } else { printf(); exit(1); } } bool pop(stack_of_bool *sp) { if (!is_empty(sp)) return sp->els[(sp->top)--]; else { printf(); exit(1); } } void make_empty(stack_of_bool *sp) { sp->top = -1; } int elems_count(stack_of_bool *sp) { return (sp->top) + 1; } bool is_operator(const char c) { return c == '&' || c == '|' || c == '!' || c == '^'; } int vars_index(const char c) { int i; for (i = 0; i < vars_len; ++i) { if (vars[i].name == c) return i; } return -1; } bool eval_expr() { int i, vi; char e; stack_of_bool s; stack_of_bool *sp = &s; make_empty(sp); for (i = 0; i < expr_len; ++i) { e = expr[i]; if (e == 'T') push(sp, TRUE); else if (e == 'F') push(sp, FALSE); else if((vi = vars_index(e)) >= 0) { push(sp, vars[vi].val); } else switch(e) { case '&': push(sp, pop(sp) & pop(sp)); break; case '|': push(sp, pop(sp) | pop(sp)); break; case '!': push(sp, !pop(sp)); break; case '^': push(sp, pop(sp) ^ pop(sp)); break; default: printf(, e); exit(1); } } if (elems_count(sp) != 1) { printf(); exit(1); } return peek(sp); } void set_vars(int pos) { int i; if (pos > vars_len) { printf(); exit(1); } else if (pos == vars_len) { for (i = 0; i < vars_len; ++i) { printf((vars[i].val) ? : ); } printf(, (eval_expr()) ? 'T' : 'F'); } else { vars[pos].val = FALSE; set_vars(pos + 1); vars[pos].val = TRUE; set_vars(pos + 1); } } void process_expr() { int i, count = 0; for (i = 0; expr[i]; ++i) { if (!isspace(expr[i])) expr[count++] = toupper(expr[i]); } expr[count] = '\0'; } int main() { int i, h; char e; printf(); printf(); printf(); printf(); while (TRUE) { printf(); fgets(expr, BUFFER_SIZE, stdin); fflush(stdin); process_expr(); expr_len = strlen(expr); if (expr_len == 0) break; vars_len = 0; for (i = 0; i < expr_len; ++i) { e = expr[i]; if (!is_operator(e) && e != 'T' && e != 'F' && vars_index(e) == -1) { vars[vars_len].name = e; vars[vars_len].val = FALSE; vars_len++; } } printf(); if (vars_len == 0) { printf(); } else { for (i = 0; i < vars_len; ++i) printf(, vars[i].name); printf(, expr); h = vars_len * 3 + expr_len; for (i = 0; i < h; ++i) printf(); printf(); set_vars(0); } } return 0; }
98Truth table
5c
5ljuk
from __future__ import print_function import random def randN(N): return lambda: random.randrange(N) == 0 def unbiased(biased): 'uses a biased() generator of 1 or 0, to create an unbiased one' this, that = biased(), biased() while this == that: this, that = biased(), biased() return this if __name__ == '__main__': from collections import namedtuple Stats = namedtuple('Stats', 'count1 count0 percent') for N in range(3, 7): biased = randN(N) v = [biased() for x in range(1000000)] v1, v0 = v.count(1), v.count(0) print ( % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) ) v = [unbiased(biased) for x in range(1000000)] v1, v0 = v.count(1), v.count(0) print ( % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )
90Unbias a random generator
3python
3drzc
setFileSize :: FilePath -> FileOffset -> IO ()
96Truncate a file
8haskell
znlt0
package main import ( "fmt" "io" "os" "strings" ) type nNode struct { name string children []nNode } type iNode struct { level int name string } func printNest(n nNode, level int, w io.Writer) { if level == 0 { fmt.Fprintln(w, "\n==Nest form==\n") } fmt.Fprintf(w, "%s%s\n", strings.Repeat(" ", level), n.name) for _, c := range n.children { fmt.Fprintf(w, "%s", strings.Repeat(" ", level+1)) printNest(c, level+1, w) } } func toNest(iNodes []iNode, start, level int, n *nNode) { if level == 0 { n.name = iNodes[0].name } for i := start + 1; i < len(iNodes); i++ { if iNodes[i].level == level+1 { c := nNode{iNodes[i].name, nil} toNest(iNodes, i, level+1, &c) n.children = append(n.children, c) } else if iNodes[i].level <= level { return } } } func printIndent(iNodes []iNode, w io.Writer) { fmt.Fprintln(w, "\n==Indent form==\n") for _, n := range iNodes { fmt.Fprintf(w, "%d%s\n", n.level, n.name) } } func toIndent(n nNode, level int, iNodes *[]iNode) { *iNodes = append(*iNodes, iNode{level, n.name}) for _, c := range n.children { toIndent(c, level+1, iNodes) } } func main() { n1 := nNode{"RosettaCode", nil} n2 := nNode{"rocks", []nNode{{"code", nil}, {"comparison", nil}, {"wiki", nil}}} n3 := nNode{"mocks", []nNode{{"trolling", nil}}} n1.children = append(n1.children, n2, n3) var sb strings.Builder printNest(n1, 0, &sb) s1 := sb.String() fmt.Print(s1) var iNodes []iNode toIndent(n1, 0, &iNodes) printIndent(iNodes, os.Stdout) var n nNode toNest(iNodes, 0, 0, &n) sb.Reset() printNest(n, 0, &sb) s2 := sb.String() fmt.Print(s2) fmt.Println("\nRound trip test satisfied? ", s1 == s2) }
99Tree datastructures
0go
2m4l7
randN = function(N) sample.int(N, 1) == 1 unbiased = function(f) {while ((x <- f()) == f()) {} x} samples = 10000 print(t(round(d = 2, sapply(3:6, function(N) c( N = N, biased = mean(replicate(samples, randN(N))), unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))
90Unbias a random generator
13r
d8unt
import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class TruncFile { public static void main(String[] args) throws IOException{ if(args.length < 2){ System.out.println("Usage: java TruncFile fileName newSize"); return; }
96Truncate a file
9java
oq38d
import Data.List (span) data Nest a = Nest (Maybe a) [Nest a] deriving Eq instance Show a => Show (Nest a) where show (Nest (Just a) []) = show a show (Nest (Just a) s) = show a ++ show s show (Nest Nothing []) = "\"\"" show (Nest Nothing s) = "\"\"" ++ show s type Indent a = [(Int, a)] class Iso b a => Iso a b where from :: a -> b instance Iso (Nest a) (Indent a) where from = go (-1) where go n (Nest a t) = case a of Just a -> (n, a): foldMap (go (n + 1)) t Nothing -> foldMap (go (n + 1)) t instance Iso (Indent a) (Nest a) where from = revNest . foldl add (Nest Nothing []) where add t (d,x) = go 0 t where go n (Nest a s) = case compare n d of EQ -> Nest a $ Nest (Just x) []: s LT -> case s of h:t -> Nest a $ go (n+1) h: t [] -> go n $ Nest a [Nest Nothing []] GT -> go (n-1) $ Nest Nothing [Nest a s] revNest (Nest a s) = Nest a (reverse $ revNest <$> s) instance Iso (Indent String) String where from = unlines . map process where process (d, s) = replicate (4*d) ' ' ++ s instance Iso String (Indent String) where from = map process . lines where process s = let (i, a) = span (== ' ') s in (length i `div` 4, a) instance Iso (Nest String) String where from = from @(Indent String) . from instance Iso String (Nest String) where from = from @(Indent String) . from
99Tree datastructures
8haskell
akq1g
(use '[clojure.math.combinatorics] (defn xor? [& args] (odd? (count (filter identity args)))) (defn twelve-statements [] (for [[a b c d e f g h i j k l] (selections [true false] 12) :when (true? a) :when (if (= 3 (count (filter true? [g h i j k l]))) (true? b) (false? b)) :when (if (= 2 (count (filter true? [b d f h j l]))) (true? c) (false? c)) :when (if (or (false? e) (every? true? [e f g])) (true? d) (false? d)) :when (if (every? false? [b c d]) (true? e) (false? e)) :when (if (= 4 (count (filter true? [a c e g i k]))) (true? f) (false? f)) :when (if (xor? (true? b) (true? c)) (true? g) (false? g)) :when (if (or (false? g) (every? true? [e f g])) (true? h) (false? h)) :when (if (= 3 (count (filter true? [a b c d e f]))) (true? i) (false? i)) :when (if (every? true? [k l]) (true? j) (false? j)) :when (if (= 1 (count (filter true? [g h i]))) (true? k) (false? k)) :when (if (= 4 (count (filter true? [a b c d e f g h i j k]))) (true? l) (false? l))] [a b c d e f g h i j k l]))
100Twelve statements
6clojure
c6v9b
require 'prime' (1..8).each do |n| count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2} puts end
95Twin primes
14ruby
42p5p
null
88Unprimeable numbers
15rust
1hzpu
null
96Truncate a file
11kotlin
x1nws
use strict; use warnings; use feature 'say'; use JSON; use Data::Printer; my $trees = <<~END; RosettaCode encourages code diversity comparison discourages golfing trolling emphasising execution speed code-golf.io encourages golfing discourages comparison END my $level = ' '; sub nested_to_indent { shift =~ s sub indent_to_nested { shift =~ s say my $indent = nested_to_indent $trees; my $nest = indent_to_nested $indent; use Test::More; is($trees, $nest, 'Round-trip'); done_testing(); sub import { my($trees) = @_; my $level = ' '; my $forest; my $last = -999; for my $branch (split /\n/, $trees) { $branch =~ m/(($level*))*/; my $this = $1 ? length($1)/length($level) : 0; $forest .= do { if ($this gt $last) { '[' . trim_and_quote($branch) } elsif ($this lt $last) { ']'x($last-$this).',' . trim_and_quote($branch) } else { trim_and_quote($branch) } }; $last = $this; } sub trim_and_quote { shift =~ s/^\s*(.*\S)\s*$/"$1",/r } eval $forest . ']' x (1+$last); } my $forest = import $trees; say "Native data structure:\n" . np $forest; say "\nJSON:\n" . encode_json($forest);
99Tree datastructures
2perl
oqf8x
(ns clojure-sandbox.truthtables (:require [clojure.string:as s] [clojure.pprint:as pprint])) (defn !op [expr] (not expr)) (defn |op [e1 e2] (not (and (not e1) (not e2)))) (defn &op [e1 e2] (and e1 e2)) (defn ->op [e1 e2] (if e1 e2 true)) (def operators {"!" !op "|" |op "&" &op "->" ->op}) (defn evaluate-unary [operator operand valuemap] (let [operand-value (value operand valuemap) operator (get operators operator)] (operator operand-value))) (defn evaluate-binary [o1 op o2 valuemap] (let [op1-value (value o1 valuemap) op2-value (value o2 valuemap) operator (get operators op)] (operator op1-value op2-value))) (defprotocol Expression (value [_ valuemap] "Returns boolean value of expression")) (defrecord UnaryExpression [operator operand] Expression (value [self valuemap] (evaluate-unary operator operand valuemap))) (defrecord BinaryExpression [op1 operator op2] Expression (value [self valuemap] (evaluate-binary op1 operator op2 valuemap))) (defrecord SymbolExpression [operand] Expression (value [self valuemap] (get valuemap operand))) (defn expression [inputs] (if (contains? operators (first inputs)) (->UnaryExpression (first inputs) (expression (rest inputs))) (if (= 1 (count inputs)) (->SymbolExpression (first inputs)) (->BinaryExpression (->SymbolExpression (first inputs)) (nth inputs 1) (expression (nthrest inputs (- (count inputs) 1))))))) (defn parse [input-str] (-> input-str s/trim (s/split #"\s+"))) (defn extract-var-names [inputs] "Get a list of variables that can have truth value" (->> inputs (filter (fn[i] (not (contains? operators i)))) set)) (defn all-var-values [inputs] "Returns a list of all potential variable assignments" (let [vars (extract-var-names inputs)] (loop [vars-left vars outputs []] (if (empty? vars-left) outputs (let [this-var (first vars-left)] (if (empty? outputs) (recur (rest vars-left) [{this-var true} {this-var false}]) (recur (rest vars-left) (concat (map (fn[x] (assoc x this-var true)) outputs) (map (fn[x] (assoc x this-var false)) outputs))))))))) (defn truth-table [input] "Print out the truth table for an input string" (let [input-values (parse input) value-maps (all-var-values input-values) expression (expression input-values)] (value expression (first value-maps)) (->> value-maps (map (fn [x] (assoc x input (value expression x)))) pprint/print-table))) (truth-table "! a | b")
98Truth table
6clojure
j417m
null
95Twin primes
15rust
gv14o
package main import "fmt" type any = interface{} func toTree(list []int) any { s := []any{[]any{}} for _, n := range list { for n != len(s) { if n > len(s) { inner := []any{} s[len(s)-1] = append(s[len(s)-1].([]any), inner) s = append(s, inner) } else { s = s[0 : len(s)-1] } } s[len(s)-1] = append(s[len(s)-1].([]any), n) for i := len(s) - 2; i >= 0; i-- { le := len(s[i].([]any)) s[i].([]any)[le-1] = s[i+1] } } return s[0] } func main() { tests := [][]int{ {}, {1, 2, 4}, {3, 1, 3, 1}, {1, 2, 3, 1}, {3, 2, 1, 3}, {3, 3, 3, 1, 1, 3, 3, 3}, } for _, test := range tests { nest := toTree(test) fmt.Printf("%17s =>%v\n", fmt.Sprintf("%v", test), nest) } }
101Tree from nesting levels
0go
n0fi1
import Foundation class BitArray { var array: [UInt32] init(size: Int) { array = Array(repeating: 0, count: (size + 31)/32) } func get(index: Int) -> Bool { let bit = UInt32(1) << (index & 31) return (array[index >> 5] & bit)!= 0 } func set(index: Int, value: Bool) { let bit = UInt32(1) << (index & 31) if value { array[index >> 5] |= bit } else { array[index >> 5] &= ~bit } } } class PrimeSieve { let composite: BitArray init(size: Int) { composite = BitArray(size: size/2) var p = 3 while p * p <= size { if!composite.get(index: p/2 - 1) { let inc = p * 2 var q = p * p while q <= size { composite.set(index: q/2 - 1, value: true) q += inc } } p += 2 } } func isPrime(number: Int) -> Bool { if number < 2 { return false } if (number & 1) == 0 { return number == 2 } return!composite.get(index: number/2 - 1) } }
88Unprimeable numbers
17swift
b7fkd
def rand_n(bias) rand(bias) == 0? 1: 0 end def unbiased(bias) a, b = rand_n(bias), rand_n(bias) until a!= b a end runs = 1_000_000 keys = %i(bias biased unbiased) puts keys.join() (3..6).each do |bias| counter = Hash.new(0) runs.times do counter[:biased] += 1 if rand_n(bias) == 1 counter[:unbiased] += 1 if unbiased(bias) == 1 end counter[:bias] = bias puts counter.values_at(*keys).join() end
90Unbias a random generator
14ruby
ytj6n
function truncate (filename, length) local inFile = io.open(filename, 'r') if not inFile then error("Specified filename does not exist") end local wholeFile = inFile:read("*all") inFile:close() if length >= wholeFile:len() then error("Provided length is not less than current file length") end local outFile = io.open(filename, 'w') outFile:write(wholeFile:sub(1, length)) outFile:close() end
96Truncate a file
1lua
qadx0
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: level = [] while lst: d, name = lst[0] if d == depth: children = [] level.append((name, children)) lst.pop(0) elif d > depth: to_nest(lst, d, children) elif d < depth: return return level[0] if level else None if __name__ == '__main__': print('Start Nest format:') nest = ('RosettaCode', [('rocks', [('code', []), ('comparison', []), ('wiki', [])]), ('mocks', [('trolling', [])])]) pp(nest, width=25) print('\n... To Indent format:') as_ind = to_indent(nest) pp(as_ind, width=25) print('\n... To Nest format:') as_nest = to_nest(as_ind) pp(as_nest, width=25) if nest != as_nest: print()
99Tree datastructures
3python
istof
#![feature(inclusive_range_syntax)] extern crate rand; use rand::Rng; fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize { rng.gen_weighted_bool(n) as usize
90Unbias a random generator
15rust
mzhya
def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop } for( i <- (3 until 7) ) println { val m = 50000 var c1,c2 = 0 (0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2 += 1 } "%d:%2.2f%% %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m) }
90Unbias a random generator
16scala
lypcq
import Data.Bifunctor (bimap) import Data.Tree (Forest, Tree (..), drawTree, foldTree) treeFromSparseLevels :: [Int] -> Tree (Maybe Int) treeFromSparseLevels = Node Nothing . forestFromNestLevels . rooted . normalised sparseLevelsFromTree :: Tree (Maybe Int) -> [Int] sparseLevelsFromTree = foldTree go where go Nothing xs = concat xs go (Just x) xs = x: concat xs forestFromNestLevels :: [(Int, a)] -> Forest a forestFromNestLevels = go where go [] = [] go ((n, v): xs) = uncurry (:) $ bimap (Node v . go) go (span ((n <) . fst) xs) main :: IO () main = mapM_ ( \xs -> putStrLn ("From: " <> show xs) >> let tree = treeFromSparseLevels xs in putStrLn ((drawTree . fmap show) tree) >> putStrLn ( "Back to: " <> show (sparseLevelsFromTree tree) <> "\n\n" ) ) [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3] ] rooted :: [(Int, Maybe Int)] -> [(Int, Maybe Int)] rooted [] = [] rooted xs = go $ filter ((1 <=) . fst) xs where go xs@((1, mb): _) = xs go xs@((n, mb): _) = fmap (,Nothing) [1 .. pred n] <> xs normalised [] = [] normalised [x] = [(x, Just x)] normalised (x: y: xs) | 1 < (y - x) = (x, Just x): (succ x, Nothing): normalised (y: xs) | otherwise = (x, Just x): normalised (y: xs)
101Tree from nesting levels
8haskell
uc4v2
char *primes; int n_primes; void init_primes() { int j; primes = malloc(sizeof(char) * MAX_PRIME); memset(primes, 1, MAX_PRIME); primes[0] = primes[1] = 0; int i = 2; while (i * i < MAX_PRIME) { for (j = i * 2; j < MAX_PRIME; j += i) primes[j] = 0; while (++i < MAX_PRIME && !primes[i]); } } int left_trunc(int n) { int tens = 1; while (tens < n) tens *= 10; while (n) { if (!primes[n]) return 0; tens /= 10; if (n < tens) return 0; n %= tens; } return 1; } int right_trunc(int n) { while (n) { if (!primes[n]) return 0; n /= 10; } return 1; } int main() { int n; int max_left = 0, max_right = 0; init_primes(); for (n = MAX_PRIME - 1; !max_left; n -= 2) if (left_trunc(n)) max_left = n; for (n = MAX_PRIME - 1; !max_right; n -= 2) if (right_trunc(n)) max_right = n; printf(, max_left, max_right); return 0; }
102Truncatable primes
5c
8xo04
package main import ( "math" "fmt" ) type Direction byte const ( RIGHT Direction = iota UP LEFT DOWN ) func generate(n,i int, c byte) { s := make([][]string, n) for i := 0; i < n; i++ { s[i] = make([]string, n) } dir := RIGHT y := n / 2 var x int if (n % 2 == 0) { x = y - 1 } else { x = y }
97Ulam spiral (for primes)
0go
oqz8q
open FOO, ">>file" or die; truncate(FOO, 1234); close FOO; truncate("file", 567);
96Truncate a file
2perl
2m7lf
use strict; use warnings; use Data::Dump qw(dd pp); my @tests = ( [] ,[1, 2, 4] ,[3, 1, 3, 1] ,[1, 2, 3, 1] ,[3, 2, 1, 3] ,[3, 3, 3, 1, 1, 3, 3, 3] ); for my $before ( @tests ) { dd { before => $before }; local $_ = (pp $before) =~ s/\d+/ '['x($&-1) . $& . ']'x($&-1) /ger; 1 while s/\](,\s*)\[/$1/; my $after = eval; dd { after => $after }; }
101Tree from nesting levels
2perl
krphc
import Data.List import Data.Numbers.Primes ulam n representation = swirl n . map representation
97Ulam spiral (for primes)
8haskell
2mrll
package main import "fmt"
100Twelve statements
0go
b7akh
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) return } if !tt(in.Text()) { return } } } func tt(expr string) bool {
98Truth table
0go
8xf0g
(use '[clojure.contrib.lazy-seqs:only [primes]]) (def prime? (let [mem (ref #{}) primes (ref primes)] (fn [n] (dosync (if (< n (first @primes)) (@mem n) (let [[mems ss] (split-with #(<= % n) @primes)] (ref-set primes ss) ((commute mem into mems) n))))))) (defn drop-lefts [n] (let [dropl #(if (< % 10) 0 (Integer. (subs (str %) 1)))] (->> (iterate dropl n) (take-while pos? ,) next))) (defn drop-rights [n] (->> (iterate #(quot % 10) n) next (take-while pos? ,))) (defn truncatable-left? [n] (every? prime? (drop-lefts n))) (defn truncatable-right? [n] (every? prime? (drop-rights n))) user> (->> (for [p primes :while (< p 1000000) :when (not-any? #{\0} (str p)) :let [l? (if (truncatable-left? p) p 0) r? (if (truncatable-right? p) p 0)] :when (or l? r?)] [l? r?]) ((juxt #(apply max-key first %) #(apply max-key second %)) ,) ((juxt ffirst (comp second second)) ,) (map vector ["left truncatable: " "right truncatable: "] ,)) (["left truncatable: " 998443] ["right truncatable: " 739399])
102Truncatable primes
6clojure
fotdm
def to_tree(x, index=0, depth=1): so_far = [] while index < len(x): this = x[index] if this == depth: so_far.append(this) elif this > depth: index, deeper = to_tree(x, index, depth + 1) so_far.append(deeper) else: index -=1 break index += 1 return (index, so_far) if depth > 1 else so_far if __name__ == : from pprint import pformat def pnest(nest:list, width: int=9) -> str: text = pformat(nest, width=width).replace('\n', '\n ') print(f) exercises = [ [], [1, 2, 4], [3, 1, 3, 1], [1, 2, 3, 1], [3, 2, 1, 3], [3, 3, 3, 1, 1, 3, 3, 3], ] for flat in exercises: nest = to_tree(flat) print(f) pnest(nest)
101Tree from nesting levels
3python
b71kr
enum Rule { r01( 1, { r()*.num == (1..12) }), r02( 2, { r(7..12).count { it.truth } == 3 }), r03( 3, { r(2..12, 2).count { it.truth } == 2 }), r04( 4, { r(5).truth ? r(6).truth && r(7).truth: true }), r05( 5, { r(2..4).count { it.truth } == 0 }), r06( 6, { r(1..11, 2).count { it.truth } == 4 }), r07( 7, { r(2).truth != r(3).truth }), r08( 8, { r(7).truth ? r(5).truth && r(6).truth: true }), r09( 9, { r(1..6).count { it.truth } == 3 }), r10(10, { r(11).truth && r(12).truth }), r11(11, { r(7..9).count { it.truth } == 1 }), r12(12, { r(1..11).count { it.truth } == 4 }); final int num final Closure statement boolean truth static final List<Rule> rules = [ null, r01, r02, r03, r04, r05, r06, r07, r08, r09, r10, r11, r12] private Rule(num, statement) { this.num = num this.statement = statement } public static Rule r(int index) { rules[index] } public static List<Rule> r() { rules[1..12] } public static List<Rule> r(List<Integer> indices) { rules[indices] } public static List<Rule> r(IntRange indices) { rules[indices] } public static List<Rule> r(IntRange indices, int step) { r(indices.step(step)) } public static void setAllTruth(int bits) { (1..12).each { r(it).truth = !(bits & (1 << (12 - it))) } } public static void evaluate() { def nearMisses = [:] (0..<(2**12)).each { i -> setAllTruth(i) def truthCandidates = r().findAll { it.truth } def truthMatchCount = r().count { it.statement() == it.truth } if (truthMatchCount == 12) { println ">Solution< ${truthCandidates*.num}" } else if (truthMatchCount == 11) { def miss = (1..12).find { r(it).statement() != r(it).truth } nearMisses << [(truthCandidates): miss] } } nearMisses.each { truths, miss -> printf ("Near Miss:%-21s (failed%2d)\n", "${truths*.num}", miss) } } } Rule.evaluate()
100Twelve statements
7groovy
ruhgh
import Control.Monad (mapM, foldM, forever) import Data.List (unwords, unlines, nub) import Data.Maybe (fromJust) truthTable expr = let tokens = words expr operators = ["&", "|", "!", "^", "=>"] variables = nub $ filter (not . (`elem` operators)) tokens table = zip variables <$> mapM (const [True,False]) variables results = map (\r -> (map snd r) ++ (calculate tokens) r) table header = variables ++ ["result"] in showTable $ header: map (map show) results calculate :: [String] -> [(String, Bool)] -> [Bool] calculate = foldM interprete [] where interprete (x:y:s) "&" = (: s) <$> pure (x && y) interprete (x:y:s) "|" = (: s) <$> pure (x || y) interprete (x:y:s) "^" = (: s) <$> pure (x /= y) interprete (x:y:s) "=>" = (: s) <$> pure (not y || x) interprete (x:s) "!" = (: s) <$> pure (not x) interprete s var = (: s) <$> fromJust . lookup var showTable tbl = unlines $ map (unwords . map align) tbl where align txt = take colWidth $ txt ++ repeat ' ' colWidth = max 6 $ maximum $ map length (head tbl) main = forever $ getLine >>= putStrLn . truthTable
98Truth table
8haskell
ly4ch
import java.util.Arrays; public class Ulam{ enum Direction{ RIGHT, UP, LEFT, DOWN; } private static String[][] genUlam(int n){ return genUlam(n, 1); } private static String[][] genUlam(int n, int i){ String[][] spiral = new String[n][n]; Direction dir = Direction.RIGHT; int j = i; int y = n / 2; int x = (n % 2 == 0) ? y - 1: y;
97Ulam spiral (for primes)
9java
6f23z
def truncate_file(name, length): if not os.path.isfile(name): return False if length >= os.path.getsize(name): return False with open(name, 'ab') as f: f.truncate(length) return True
96Truncate a file
3python
v9j29
truncate_file <- function(filename, n_bytes) { stopifnot( "file does not exist"= file.exists(filename), "not enough bytes in file"= file.size(filename) >= n_bytes ) input.con <- file(filename, "rb") bindata <- readBin(input.con, integer(), n=n_bytes/4) close(input.con) tmp.filename <- tempfile() output.con <- file(tmp.filename, "wb") writeBin(bindata, output.con) close(output.con) stopifnot( "temp file is not expected size"= file.size(tmp.filename) == n_bytes ) file.rename(tmp.filename, filename) }
96Truncate a file
13r
934mg
import Data.List (findIndices) tf :: [[Int] -> Bool] -> [[Int]] tf = traverse (const [1, 0]) wrongness :: [Int] -> [[Int] -> Bool] -> [Int] wrongness ns ps = findIndices id (zipWith (/=) ns (map (fromEnum . ($ ns)) ps)) statements :: [[Int] -> Bool] statements = [ (== 12) . length , 3 [length statements - 6 ..] , 2 [1,3 ..] , 4 [4 .. 6] , 0 [1 .. 3] , 4 [0,2 ..] , 1 [1, 2] , 6 [4 .. 6] , 3 [0 .. 5] , 2 [10, 11] , 1 [6, 7, 8] , 4 [0 .. 10] ] where (), () :: Int -> [Int] -> [Int] -> Bool (s x) b = s == (sum . map (b !!) . takeWhile (< length b)) x (a x) b = (b !! a == 0) || all ((== 1) . (b !!)) x testall :: [[Int] -> Bool] -> Int -> [([Int], [Int])] testall s n = [ (b, w) | b <- tf s , w <- [wrongness b s] , length w == n ] main :: IO () main = let t = testall statements in do putStrLn "Answer" mapM_ print $ t 0 putStrLn "Near misses" mapM_ print $ t 1
100Twelve statements
8haskell
d8zn4
<!-- UlamSpiral.html --> <html> <head><title>Ulam Spiral</title> <script src="VOE.js"></script> <script>
97Ulam spiral (for primes)
10javascript
lygcf
enum { LEFT, RIGHT, STAY }; typedef struct { int state1; int symbol1; int symbol2; int dir; int state2; } transition_t; typedef struct tape_t tape_t; struct tape_t { int symbol; tape_t *left; tape_t *right; }; typedef struct { int states_len; char **states; int final_states_len; int *final_states; int symbols_len; char *symbols; int blank; int state; int tape_len; tape_t *tape; int transitions_len; transition_t ***transitions; } turing_t; int state_index (turing_t *t, char *state) { int i; for (i = 0; i < t->states_len; i++) { if (!strcmp(t->states[i], state)) { return i; } } return 0; } int symbol_index (turing_t *t, char symbol) { int i; for (i = 0; i < t->symbols_len; i++) { if (t->symbols[i] == symbol) { return i; } } return 0; } void move (turing_t *t, int dir) { tape_t *orig = t->tape; if (dir == RIGHT) { if (orig && orig->right) { t->tape = orig->right; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->left = orig; orig->right = t->tape; } } } else if (dir == LEFT) { if (orig && orig->left) { t->tape = orig->left; } else { t->tape = calloc(1, sizeof (tape_t)); t->tape->symbol = t->blank; if (orig) { t->tape->right = orig; orig->left = t->tape; } } } } turing_t *create (int states_len, ...) { va_list args; va_start(args, states_len); turing_t *t = malloc(sizeof (turing_t)); t->states_len = states_len; t->states = malloc(states_len * sizeof (char *)); int i; for (i = 0; i < states_len; i++) { t->states[i] = va_arg(args, char *); } t->final_states_len = va_arg(args, int); t->final_states = malloc(t->final_states_len * sizeof (int)); for (i = 0; i < t->final_states_len; i++) { t->final_states[i] = state_index(t, va_arg(args, char *)); } t->symbols_len = va_arg(args, int); t->symbols = malloc(t->symbols_len); for (i = 0; i < t->symbols_len; i++) { t->symbols[i] = va_arg(args, int); } t->blank = symbol_index(t, va_arg(args, int)); t->state = state_index(t, va_arg(args, char *)); t->tape_len = va_arg(args, int); t->tape = NULL; for (i = 0; i < t->tape_len; i++) { move(t, RIGHT); t->tape->symbol = symbol_index(t, va_arg(args, int)); } if (!t->tape_len) { move(t, RIGHT); } while (t->tape->left) { t->tape = t->tape->left; } t->transitions_len = va_arg(args, int); t->transitions = malloc(t->states_len * sizeof (transition_t **)); for (i = 0; i < t->states_len; i++) { t->transitions[i] = malloc(t->symbols_len * sizeof (transition_t *)); } for (i = 0; i < t->transitions_len; i++) { transition_t *tran = malloc(sizeof (transition_t)); tran->state1 = state_index(t, va_arg(args, char *)); tran->symbol1 = symbol_index(t, va_arg(args, int)); tran->symbol2 = symbol_index(t, va_arg(args, int)); tran->dir = va_arg(args, int); tran->state2 = state_index(t, va_arg(args, char *)); t->transitions[tran->state1][tran->symbol1] = tran; } va_end(args); return t; } void print_state (turing_t *t) { printf(, t->states[t->state]); tape_t *tape = t->tape; while (tape->left) { tape = tape->left; } while (tape) { if (tape == t->tape) { printf(, t->symbols[tape->symbol]); } else { printf(, t->symbols[tape->symbol]); } tape = tape->right; } printf(); } void run (turing_t *t) { int i; while (1) { print_state(t); for (i = 0; i < t->final_states_len; i++) { if (t->final_states[i] == t->state) { return; } } transition_t *tran = t->transitions[t->state][t->tape->symbol]; t->tape->symbol = tran->symbol2; move(t, tran->dir); t->state = tran->state2; } } int main () { printf(); turing_t *t = create( 2, , , 1, , 2, 'B', '1', 'B', , 3, '1', '1', '1', 2, , '1', '1', RIGHT, , , 'B', '1', STAY, ); run(t); printf(); t = create( 4, , , , , 1, , 2, '0', '1', '0', , 0, 6, , '0', '1', RIGHT, , , '1', '1', LEFT, , , '0', '1', LEFT, , , '1', '1', RIGHT, , , '0', '1', LEFT, , , '1', '1', STAY, ); run(t); return 0; printf(); t = create( 6, , , , , , , 1, , 2, '0', '1', '0', , 0, 10, , '0', '1', RIGHT, , , '1', '1', LEFT, , , '0', '1', RIGHT, , , '1', '1', RIGHT, , , '0', '1', RIGHT, , , '1', '0', LEFT, , , '0', '1', LEFT, , , '1', '1', LEFT, , , '0', '1', STAY, , , '1', '0', LEFT, ); run(t); }
103Universal Turing machine
5c
sesq5
public class LogicPuzzle { boolean S[] = new boolean[13]; int Count = 0; public boolean check2 () { int count = 0; for (int k = 7; k <= 12; k++) if (S[k]) count++; return S[2] == (count == 3); } public boolean check3 () { int count = 0; for (int k = 2; k <= 12; k += 2) if (S[k]) count++; return S[3] == (count == 2); } public boolean check4 () { return S[4] == ( !S[5] || S[6] && S[7]); } public boolean check5 () { return S[5] == ( !S[2] && !S[3] && !S[4]); } public boolean check6 () { int count = 0; for (int k = 1; k <= 11; k += 2) if (S[k]) count++; return S[6] == (count == 4); } public boolean check7 () { return S[7] == ((S[2] || S[3]) && !(S[2] && S[3])); } public boolean check8 () { return S[8] == ( !S[7] || S[5] && S[6]); } public boolean check9 () { int count = 0; for (int k = 1; k <= 6; k++) if (S[k]) count++; return S[9] == (count == 3); } public boolean check10 () { return S[10] == (S[11] && S[12]); } public boolean check11 () { int count = 0; for (int k = 7; k <= 9; k++) if (S[k]) count++; return S[11] == (count == 1); } public boolean check12 () { int count = 0; for (int k = 1; k <= 11; k++) if (S[k]) count++; return S[12] == (count == 4); } public void check () { if (check2() && check3() && check4() && check5() && check6() && check7() && check8() && check9() && check10() && check11() && check12()) { for (int k = 1; k <= 12; k++) if (S[k]) System.out.print(k + " "); System.out.println(); Count++; } } public void recurseAll (int k) { if (k == 13) check(); else { S[k] = false; recurseAll(k + 1); S[k] = true; recurseAll(k + 1); } } public static void main (String args[]) { LogicPuzzle P = new LogicPuzzle(); P.S[1] = true; P.recurseAll(2); System.out.println(); System.out.println(P.Count + " Solutions found."); } }
100Twelve statements
9java
seoq0
import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; public class TruthTable { public static void main( final String... args ) { System.out.println( new TruthTable( args ) ); } private interface Operator { boolean evaluate( Stack<Boolean> s ); } private static final Map<String,Operator> operators = new HashMap<String,Operator>() {{
98Truth table
9java
3dczg
File.open(, ) do |f| f.truncate(1234) f << end File.truncate(, 567)
96Truncate a file
14ruby
5lkuj
use std::path::Path; use std::fs; fn truncate_file<P: AsRef<Path>>(filename: P, filesize: usize) -> Result<(), Error> { use Error::*; let file = fs::read(&filename).or(Err(NotFound))?; if filesize > file.len() { return Err(FilesizeTooSmall) } fs::write(&filename, &file[..filesize]).or(Err(UnableToWrite))?; Ok(()) } #[derive(Debug)] enum Error {
96Truncate a file
15rust
42b5u
typedef struct { char v[16]; } deck; typedef unsigned int uint; uint n, d, best[16]; void tryswaps(deck *a, uint f, uint s) { if (d > best[n]) best[n] = d; while (1) { if ((A[s] == s || (A[s] == -1 && !(f & 1U << s))) && (d + best[s] >= best[n] || A[s] == -1)) break; if (d + best[s] <= best[n]) return; if (!--s) return; } d++; deck b = *a; for (uint i = 1, k = 2; i <= s; k <<= 1, i++) { if (A[i] != i && (A[i] != -1 || (f & k))) continue; for (uint j = B[0] = i; j--;) B[i - j] = A[j]; tryswaps(&b, f | k, s); } d--; } int main(void) { deck x; memset(&x, -1, sizeof(x)); x.v[0] = 0; for (n = 1; n < 13; n++) { tryswaps(&x, 1, n - 1); printf(, n, best[n]); } return 0; }
104Topswops
5c
ox080
<!DOCTYPE html><html><head><title>Truth table</title><script> var elem,expr,vars; function isboolop(chr){return "&|!^".indexOf(chr)!=-1;} function varsindexof(chr){ var i; for(i=0;i<vars.length;i++){if(vars[i][0]==chr)return i;} return -1; } function printtruthtable(){ var i,str; elem=document.createElement("pre"); expr=prompt("Boolean expression:\nAccepts single-character variables (except for \"T\" and \"F\", which specify explicit true or false values), postfix, with \"&|!^\" for and, or, not, xor, respectively; optionally seperated by whitespace.").replace(/\s/g,""); vars=[]; for(i=0;i<expr.length;i++)if(!isboolop(expr[i])&&expr[i]!="T"&&expr[i]!="F"&&varsindexof(expr[i])==-1)vars.push([expr[i],-1]); if(vars.length==0)return; str=""; for(i=0;i<vars.length;i++)str+=vars[i][0]+" "; elem.innerHTML="<b>"+str+expr+"</b>\n"; vars[0][1]=false; truthpartfor(1); vars[0][1]=true; truthpartfor(1); vars[0][1]=-1; document.body.appendChild(elem); } function truthpartfor(index){ if(index==vars.length){ var str,i; str=""; for(i=0;i<index;i++)str+=(vars[i][1]?"<b>T</b>":"F")+" "; elem.innerHTML+=str+(parsebool()?"<b>T</b>":"F")+"\n"; return; } vars[index][1]=false; truthpartfor(index+1); vars[index][1]=true; truthpartfor(index+1); vars[index][1]=-1; } function parsebool(){ var stack,i,idx; console.log(vars); stack=[]; for(i=0;i<expr.length;i++){ if(expr[i]=="T")stack.push(true); else if(expr[i]=="F")stack.push(false); else if((idx=varsindexof(expr[i]))!=-1)stack.push(vars[idx][1]); else if(isboolop(expr[i])){ switch(expr[i]){ case "&":stack.push(stack.pop()&stack.pop());break; case "|":stack.push(stack.pop()|stack.pop());break; case "!":stack.push(!stack.pop());break; case "^":stack.push(stack.pop()^stack.pop());break; } } else alert("Non-conformant character "+expr[i]+" in expression. Should not be possible."); console.log(stack); } return stack[0]; } </script></head><body onload="printtruthtable()"></body></html>
98Truth table
10javascript
c659j
import java.io.FileOutputStream object TruncFile extends App { if (args.length < 2) println("Usage: java TruncFile fileName newSize") else {
96Truncate a file
16scala
75ar9
null
100Twelve statements
11kotlin
akx13
object Ulam { fun generate(n: Int, i: Int = 1, c: Char = '*') { require(n > 1) val s = Array(n) { Array(n, { "" }) } var dir = Direction.RIGHT var y = n / 2 var x = if (n % 2 == 0) y - 1 else y
97Ulam spiral (for primes)
11kotlin
d8ynz
(defn tape "Creates a new tape with given blank character and tape contents" ([blank] (tape () blank () blank)) ([right blank] (tape () (first right) (rest right) blank)) ([left head right blank] [(reverse left) (or head blank) (into () right) blank])) (defn- left [[[l & ls] _ rs b] c] [ls (or l b) (conj rs c) b]) (defn- right [[ls _ [r & rs] b] c] [(conj ls c) (or r b) rs b]) (defn- stay [[ls _ rs b] c] [ls c rs b]) (defn- head [[_ c _ b]] (or c b)) (defn- pretty [[ls c rs b]] (concat (reverse ls) [[(or c b)]] rs)) (defn new-machine "Returns a function that takes a tape as input, and returns the tape after running the machine specified in `machine`." [machine] (let [rules (into {} (for [[s c c' a s'] (:rules machine)] [[s c] [c' (-> a name symbol resolve) s']])) finished? (into #{} (:terminating machine))] (fn [input-tape] (loop [state (:initial machine) tape input-tape] (if (finished? state) (pretty tape) (let [[out action new-state] (get rules [state (head tape)])] (recur new-state (action tape out))))))))
103Universal Turing machine
6clojure
n0nik
null
98Truth table
11kotlin
n03ij
local function ulamspiral(n, f) print("n = " .. n) local function isprime(p) if p < 2 then return false end if p % 2 == 0 then return p==2 end if p % 3 == 0 then return p==3 end local limit = math.sqrt(p) for f = 5, limit, 6 do if p % f == 0 or p % (f+2) == 0 then return false end end return true end local function spiral(x, y) if n%2==1 then x, y = n-1-x, n-1-y end local m = math.min(x, y, n-1-x, n-1-y) return x<y and (n-2*m-2)^2+(x-m)+(y-m) or (n-2*m)^2-(x-m)-(y-m) end for y = 0, n-1 do for x = 0, n-1 do io.write(f(isprime(spiral(x,y)))) end print() end print() end
97Ulam spiral (for primes)
1lua
fomdp
user=> 3 3 user=> (Math/pow *1 2) 9.0 user=> (Math/pow *2 0.5) 1.7320508075688772
105Topic variable
6clojure
q1ext
int main () { double inputs[11], check = 400, result; int i; printf (); for (i = 0; i < 11; i++) { scanf (, &inputs[i]); } printf (); for (i = 10; i >= 0; i--) { result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3); printf (); if (result > check) { printf (); } else { printf (, result); } } return 0; }
106Trabb Pardo–Knuth algorithm
5c
toif4
package main import ( "math" "os" "strconv" "text/template" ) func sqr(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(f*f, 'f', -1, 64) } func sqrt(x string) string { f, err := strconv.ParseFloat(x, 64) if err != nil { return "NA" } return strconv.FormatFloat(math.Sqrt(f), 'f', -1, 64) } func main() { f := template.FuncMap{"sqr": sqr, "sqrt": sqrt} t := template.Must(template.New("").Funcs(f).Parse(`. = {{.}} square: {{sqr .}} square root: {{sqrt .}} `)) t.Execute(os.Stdout, "3") }
105Topic variable
0go
yfz64
use List::Util 'sum'; my @condition = ( sub { 0 }, sub { 13==@_ }, sub { 3==sum @_[7..12] }, sub { 2==sum @_[2,4,6,8,10,12] }, sub { $_[5] ? ($_[6] and $_[7]) : 1 }, sub { !$_[2] and !$_[3] and !$_[4] }, sub { 4==sum @_[1,3,5,7,9,11] }, sub { $_[2]==1-$_[3] }, sub { $_[7] ? ($_[5] and $_[6]) : 1 }, sub { 3==sum @_[1..6] }, sub { 2==sum @_[11..12] }, sub { 1==sum @_[7,8,9] }, sub { 4==sum @_[1..11] }, ); sub miss { return grep { $condition[$_]->(@_) != $_[$_] } 1..12; } for (0..2**12-1) { my @truth = split //, sprintf "0%012b", $_; my @no = miss @truth; print "Solution: true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 0 == @no; print "1 miss (",$no[0],"): true statements are ", join( " ", grep { $truth[$_] } 1..12), "\n" if 1 == @no; }
100Twelve statements
2perl
932mn
Prelude> [1..10] [1,2,3,4,5,6,7,8,9,10] Prelude> map (^2) it [1,4,9,16,25,36,49,64,81,100]
105Topic variable
8haskell
h4rju
null
105Topic variable
11kotlin
c3y98
typedef double Fp; typedef struct { Fp x, y, r; } Circle; Circle circles[] = { { 1.6417233788, 1.6121789534, 0.0848270516}, {-1.4944608174, 1.2077959613, 1.1039549836}, { 0.6110294452, -0.6907087527, 0.9089162485}, { 0.3844862411, 0.2923344616, 0.2375743054}, {-0.2495892950, -0.3832854473, 1.0845181219}, { 1.7813504266, 1.6178237031, 0.8162655711}, {-0.1985249206, -0.8343333301, 0.0538864941}, {-1.7011985145, -0.1263820964, 0.4776976918}, {-0.4319462812, 1.4104420482, 0.7886291537}, { 0.2178372997, -0.9499557344, 0.0357871187}, {-0.6294854565, -1.3078893852, 0.7653357688}, { 1.7952608455, 0.6281269104, 0.2727652452}, { 1.4168575317, 1.0683357171, 1.1016025378}, { 1.4637371396, 0.9463877418, 1.1846214562}, {-0.5263668798, 1.7315156631, 1.4428514068}, {-1.2197352481, 0.9144146579, 1.0727263474}, {-0.1389358881, 0.1092805780, 0.7350208828}, { 1.5293954595, 0.0030278255, 1.2472867347}, {-0.5258728625, 1.3782633069, 1.3495508831}, {-0.1403562064, 0.2437382535, 1.3804956588}, { 0.8055826339, -0.0482092025, 0.3327165165}, {-0.6311979224, 0.7184578971, 0.2491045282}, { 1.4685857879, -0.8347049536, 1.3670667538}, {-0.6855727502, 1.6465021616, 1.0593087096}, { 0.0152957411, 0.0638919221, 0.9771215985}}; const size_t n_circles = sizeof(circles) / sizeof(Circle); static inline Fp min(const Fp a, const Fp b) { return a <= b ? a : b; } static inline Fp max(const Fp a, const Fp b) { return a >= b ? a : b; } static inline Fp sq(const Fp a) { return a * a; } static inline double uniform(const double a, const double b) { const double r01 = rand() / (double)RAND_MAX; return a + (b - a) * r01; } static inline bool is_inside_circles(const Fp x, const Fp y) { for (size_t i = 0; i < n_circles; i++) if (sq(x - circles[i].x) + sq(y - circles[i].y) < circles[i].r) return true; return false; } int main() { Fp x_min = INFINITY, x_max = -INFINITY; Fp y_min = x_min, y_max = x_max; for (size_t i = 0; i < n_circles; i++) { Circle *c = &circles[i]; x_min = min(x_min, c->x - c->r); x_max = max(x_max, c->x + c->r); y_min = min(y_min, c->y - c->r); y_max = max(y_max, c->y + c->r); c->r *= c->r; } const Fp bbox_area = (x_max - x_min) * (y_max - y_min); srand(time(0)); size_t to_try = 1U << 16; size_t n_tries = 0; size_t n_hits = 0; while (true) { n_hits += is_inside_circles(uniform(x_min, x_max), uniform(y_min, y_max)); n_tries++; if (n_tries == to_try) { const Fp area = bbox_area * n_hits / n_tries; const Fp r = (Fp)n_hits / n_tries; const Fp s = area * sqrt(r * (1 - r) / n_tries); printf(, area, s, n_tries); if (s * 3 <= 1e-3) break; to_try *= 2; } } return 0; }
107Total circles area
5c
2yylo
print sqrt . " " for (4, 16, 64)
105Topic variable
2perl
xpaw8
null
104Topswops
0go
4lu52
>>> 3 3 >>> _*_, _**0.5 (9, 1.7320508075688772) >>>
105Topic variable
3python
q1exi
int totient(int n){ int tot = n,i; for(i=2;i*i<=n;i+=2){ if(n%i==0){ while(n%i==0) n/=i; tot-=tot/i; } if(i==2) i=1; } if(n>1) tot-=tot/n; return tot; } int main() { int count = 0,n,tot; printf(,237); printf(); for(n=1;n<=25;n++){ tot = totient(n); if(n-1 == tot) count++; printf(, n, tot, n-1 == tot?:); } printf(, 25,count); for(n = 26; n <= 100000; n++){ tot = totient(n); if(tot == n-1) count++; if(n == 100 || n == 1000 || n%10000 == 0){ printf(, n, count); } } return 0; }
108Totient function
5c
p7rby
import Data.List (permutations) topswops :: Int -> Int topswops n = maximum $ map tops $ permutations [1 .. n] where tops (1:_) = 0 tops xa@(x:_) = 1 + tops reordered where reordered = reverse (take x xa) ++ drop x xa main = mapM_ (putStrLn . ((++) <$> show <*> (":\t" ++) . show . topswops)) [1 .. 10]
104Topswops
8haskell
q1wx9
from itertools import product constraintinfo = ( (lambda st: len(st) == 12 ,(1, 'This is a numbered list of twelve statements')), (lambda st: sum(st[-6:]) == 3 ,(2, 'Exactly 3 of the last 6 statements are true')), (lambda st: sum(st[1::2]) == 2 ,(3, 'Exactly 2 of the even-numbered statements are true')), (lambda st: (st[5]&st[6]) if st[4] else 1 ,(4, 'If statement 5 is true, then statements 6 and 7 are both true')), (lambda st: sum(st[1:4]) == 0 ,(5, 'The 3 preceding statements are all false')), (lambda st: sum(st[0::2]) == 4 ,(6, 'Exactly 4 of the odd-numbered statements are true')), (lambda st: sum(st[1:3]) == 1 ,(7, 'Either statement 2 or 3 is true, but not both')), (lambda st: (st[4]&st[5]) if st[6] else 1 ,(8, 'If statement 7 is true, then 5 and 6 are both true')), (lambda st: sum(st[:6]) == 3 ,(9, 'Exactly 3 of the first 6 statements are true')), (lambda st: (st[10]&st[11]) ,(10, 'The next two statements are both true')), (lambda st: sum(st[6:9]) == 1 ,(11, 'Exactly 1 of statements 7, 8 and 9 are true')), (lambda st: sum(st[0:11]) == 4 ,(12, 'Exactly 4 of the preceding statements are true')), ) def printer(st, matches): if False in matches: print('Missed by one statement:%i,%s'% docs[matches.index(False)]) else: print('Full match:') print(' ' + ', '.join('%i:%s'% (i, 'T' if t else 'F') for i, t in enumerate(st, 1))) funcs, docs = zip(*constraintinfo) full, partial = [], [] for st in product( *([(False, True)] * 12) ): truths = [bool(func(st)) for func in funcs] matches = [s == t for s,t in zip(st, truths)] mcount = sum(matches) if mcount == 12: full.append((st, matches)) elif mcount == 11: partial.append((st, matches)) for stm in full + partial: printer(*stm)
100Twelve statements
3python
c6v9q
use ntheory qw/is_prime/; use Imager; my $n = shift || 512; my $start = shift || 1; my $file = "ulam.png"; sub cell { my($n, $x, $y, $start) = @_; $y -= $n>>1; $x -= ($n-1)>>1; my $l = 2*(abs($x) > abs($y) ? abs($x) : abs($y)); my $d = ($y > $x) ? $l*3 + $x + $y : $l-$x-$y; ($l-1)**2 + $d + $start - 1; } my $black = Imager::Color->new(' my $white = Imager::Color->new(' my $img = Imager->new(xsize => $n, ysize => $n, channels => 1); $img->box(filled=>1, color=>$white); for my $y (0 .. $n-1) { for my $x (0 .. $n-1) { my $v = cell($n, $x, $y, $start); $img->setpixel(x => $x, y => $y, color => $black) if is_prime($v); } } $img->write(file => $file) or die "Cannot write $file: ", $img->errstr, "\n";
97Ulam spiral (for primes)
2perl
j4a7f
while DATA.gets print end __END__ This is line one This is line two This is line three
105Topic variable
14ruby
0exsu
object TopicVar extends App { class SuperString(val org: String){ def it(): Unit = println(org) } new SuperString("FvdB"){it()} new SuperString("FvdB"){println(org)} Seq(1).foreach {println} Seq(2).foreach {println(_)} Seq(4).foreach { it => println(it)} Seq(8).foreach { it => println(it + it)} }
105Topic variable
16scala
ns8ic