code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
MULTIPLY = lambda x, y: x*y class num(float): def __pow__(self, b): return reduce(MULTIPLY, [self]*b, 1) print num(2).__pow__(3) print num(2) ** 3 print num(2.3).__pow__(8) print num(2.3) ** 8
874Exponentiation operator
3python
65z3w
null
879Execute a system command
1lua
n9xi8
pow <- function(x, y) { x <- as.numeric(x) y <- as.integer(y) prod(rep(x, y)) } "%pow%" <- function(x,y) pow(x,y) pow(3, 4) 2.5%pow% 2
874Exponentiation operator
13r
flndc
SELECT CASE WHEN MOD(level,15)=0 THEN 'FizzBuzz' WHEN MOD(level,3)=0 THEN 'Fizz' WHEN MOD(level,5)=0 THEN 'Buzz' ELSE TO_CHAR(level) END FizzBuzz FROM dual CONNECT BY LEVEL <= 100;
835FizzBuzz
19sql
8mn02
import Foundation func setup(ruleset: String) -> [(String, String, Bool)] { return ruleset.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) .filter { $0.rangeOfString("^s*#", options: .RegularExpressionSearch) == nil } .reduce([(String, String, Bool)]()) { rules, line in let regex = try! NSRegularExpression(pattern: "^(.+)\\s+->\\s+(\\.?)(.*)$", options: .CaseInsensitive) guard let match = regex.firstMatchInString(line, options: .Anchored, range: NSMakeRange(0, line.characters.count)) else { return rules } return rules + [( (line as NSString).substringWithRange(match.rangeAtIndex(1)), (line as NSString).substringWithRange(match.rangeAtIndex(3)), (line as NSString).substringWithRange(match.rangeAtIndex(2))!= "" )] } } func markov(ruleset: String, var input: String) -> String { let rules = setup(ruleset) var terminate = false while!terminate { guard let i = rules.indexOf ({ if let range = input.rangeOfString($0.0) { input.replaceRange(range, with: $0.1) return true } return false }) else { break } terminate = rules[i].2 } return input } let tests: [(ruleset: String, input: String)] = [ ("# This rules file is extracted from Wikipedia:\n# http:
877Execute a Markov algorithm
17swift
vkm2r
class MyException extends Exception { }
878Exceptions
12php
n9qig
class Numeric def pow(m) raise TypeError, unless m.is_a? Integer puts Array.new(m, self).reduce(1,:*) end end p 5.pow(3) p 5.5.pow(3) p 5.pow(3.1)
874Exponentiation operator
14ruby
mg6yj
extern crate num; use num::traits::One; use std::ops::Mul; fn pow<T>(mut base: T, mut exp: usize) -> T where T: Clone + One + Mul<T, Output=T> { if exp == 0 { return T::one() } while exp & 1 == 0 { base = base.clone() * base; exp >>= 1; } if exp == 1 { return base } let mut acc = base.clone(); while exp > 1 { exp >>= 1; base = base.clone() * base; if exp & 1 == 1 { acc = acc * base.clone(); } } acc }
874Exponentiation operator
15rust
9rymm
for i in 1...100 { switch (i% 3, i% 5) { case (0, 0): print("FizzBuzz") case (0, _): print("Fizz") case (_, 0): print("Buzz") default: print(i) } }
835FizzBuzz
17swift
1nwpt
import exceptions class SillyError(exceptions.Exception): def __init__(self,args=None): self.args=args
878Exceptions
3python
re2gq
object Exponentiation { import scala.annotation.tailrec @tailrec def powI[N](n: N, exponent: Int)(implicit num: Integral[N]): N = { import num._ exponent match { case 0 => one case _ if exponent % 2 == 0 => powI((n * n), (exponent / 2)) case _ => powI(n, (exponent - 1)) * n } } @tailrec def powF[N](n: N, exponent: Int)(implicit num: Fractional[N]): N = { import num._ exponent match { case 0 => one case _ if exponent < 0 => one / powF(n, exponent.abs) case _ if exponent % 2 == 0 => powF((n * n), (exponent / 2)) case _ => powF(n, (exponent - 1)) * n } } class ExponentI[N : Integral](n: N) { def \u2191(exponent: Int): N = powI(n, exponent) } class ExponentF[N : Fractional](n: N) { def \u2191(exponent: Int): N = powF(n, exponent) } object ExponentI { implicit def toExponentI[N : Integral](n: N): ExponentI[N] = new ExponentI(n) } object ExponentF { implicit def toExponentF[N : Fractional](n: N): ExponentF[N] = new ExponentF(n) } object Exponents { implicit def toExponent(n: Int): ExponentI[Int] = new ExponentI(n) implicit def toExponent(n: Double): ExponentF[Double] = new ExponentF(n) } }
874Exponentiation operator
16scala
2hclb
e <- simpleError("This is a simpleError")
878Exceptions
13r
ubmvx
package main import ( "fmt" "math/rand" "time" ) var target = []byte("METHINKS IT IS LIKE A WEASEL") var set = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ ") var parent []byte func init() { rand.Seed(time.Now().UnixNano()) parent = make([]byte, len(target)) for i := range parent { parent[i] = set[rand.Intn(len(set))] } }
880Evolutionary algorithm
0go
imeog
import System.Random import Control.Monad import Data.List import Data.Ord import Data.Array showNum :: (Num a, Show a) => Int -> a -> String showNum w = until ((>w-1).length) (' ':) . show replace :: Int -> a -> [a] -> [a] replace n c ls = take (n-1) ls ++ [c] ++ drop n ls target = "METHINKS IT IS LIKE A WEASEL" pfit = length target mutateRate = 20 popsize = 100 charSet = listArray (0,26) $ ' ': ['A'..'Z'] :: Array Int Char fitness = length . filter id . zipWith (==) target printRes i g = putStrLn $ "gen:" ++ showNum 4 i ++ " " ++ "fitn:" ++ showNum 4 (round $ 100 * fromIntegral s / fromIntegral pfit ) ++ "% " ++ show g where s = fitness g mutate :: [Char] -> Int -> IO [Char] mutate g mr = do let r = length g chances <- replicateM r $ randomRIO (1,mr) let pos = elemIndices 1 chances chrs <- replicateM (length pos) $ randomRIO (bounds charSet) let nchrs = map (charSet!) chrs return $ foldl (\ng (p,c) -> replace (p+1) c ng) g (zip pos nchrs) evolve :: [Char] -> Int -> Int -> IO () evolve parent gen mr = do when ((gen-1) `mod` 20 == 0) $ printRes (gen-1) parent children <- replicateM popsize (mutate parent mr) let child = maximumBy (comparing fitness) (parent:children) if fitness child == pfit then printRes gen child else evolve child (succ gen) mr main = do let r = length target genes <- replicateM r $ randomRIO (bounds charSet) let parent = map (charSet!) genes evolve parent 1 mutateRate
880Evolutionary algorithm
8haskell
vk32k
class SillyError < Exception end
878Exceptions
14ruby
jxu7x
null
878Exceptions
15rust
hq5j2
int factorial(int n) { int result = 1; for (int i = 1; i <= n; ++i) result *= i; return result; }
882Factorial
5c
n9ai6
null
878Exceptions
16scala
p8rbj
my @results = qx(ls); my @results = `ls`; system "ls"; print `ls`; exec "ls";
879Execute a system command
2perl
relgd
func raise<T: Numeric>(_ base: T, to exponent: Int) -> T { precondition(exponent >= 0, "Exponent has to be nonnegative") return Array(repeating: base, count: exponent).reduce(1, *) } infix operator **: MultiplicationPrecedence func **<T: Numeric>(lhs: T, rhs: Int) -> T { return raise(lhs, to: rhs) } let someFloat: Float = 2 let someInt: Int = 10 assert(raise(someFloat, to: someInt) == 1024) assert(someFloat ** someInt == 1024) assert(raise(someInt, to: someInt) == 10000000000) assert(someInt ** someInt == 10000000000)
874Exponentiation operator
17swift
y436e
package main import "fmt" func main() {
881Execute Brain****
0go
qthxz
@exec($command,$output); echo nl2br($output);
879Execute a system command
12php
dcqn8
class BrainfuckProgram { def program = '', memory = [:] def instructionPointer = 0, dataPointer = 0 def execute() { while (instructionPointer < program.size()) switch(program[instructionPointer++]) { case '>': dataPointer++; break; case '<': dataPointer--; break; case '+': memory[dataPointer] = memoryValue + 1; break case '-': memory[dataPointer] = memoryValue - 1; break case ',': memory[dataPointer] = System.in.read(); break case '.': print String.valueOf(Character.toChars(memoryValue)); break case '[': handleLoopStart(); break case ']': handleLoopEnd(); break } } private getMemoryValue() { memory[dataPointer] ?: 0 } private handleLoopStart() { if (memoryValue) return int depth = 1 while (instructionPointer < program.size()) switch(program[instructionPointer++]) { case '[': depth++; break case ']': if (!(--depth)) return } throw new IllegalStateException('Could not find matching end bracket') } private handleLoopEnd() { int depth = 0 while (instructionPointer >= 0) { switch(program[--instructionPointer]) { case ']': depth++; break case '[': if (!(--depth)) return; break } } throw new IllegalStateException('Could not find matching start bracket') } }
881Execute Brain****
7groovy
1o4p6
import java.util.Random; public class EvoAlgo { static final String target = "METHINKS IT IS LIKE A WEASEL"; static final char[] possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".toCharArray(); static int C = 100;
880Evolutionary algorithm
9java
y4i6g
null
880Evolutionary algorithm
10javascript
2hzlr
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); } // memory[border] = 0 marks the end of instructions. dp (data pointer) cannot move lower than the // border into the program area. border = dp; dp += 1; } public void execute(String program) { load(program); char instruction = memory[ip]; while (instruction!= 0) { switch (instruction) { case '>': dp++; if (dp == MEMORY_SIZE) { throw new RuntimeException("Out of memory."); } break; case '<': dp if (dp == border) { throw new RuntimeException("Invalid data pointer."); } break; case '+': memory[dp]++; break; case '-': memory[dp] break; case '.': System.out.print(memory[dp]); break; case ',': try { // Only works for one byte characters. memory[dp] = (char) System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } break; case '[': if (memory[dp] == 0) { skipLoop(); } break; case ']': if (memory[dp]!= 0) { loop(); } break; default: throw new RuntimeException("Unknown instruction."); } instruction = memory[++ip]; } } private void skipLoop() { int loopCount = 0; while (memory[ip]!= 0) { if (memory[ip] == '[') { loopCount++; } else if (memory[ip] == ']') { loopCount if (loopCount == 0) { return; } } ip++; } if (memory[ip] == 0) { throw new RuntimeException("Unable to find a matching ']'."); } } private void loop() { int loopCount = 0; while (ip >= 0) { if (memory[ip] == ']') { loopCount++; } else if (memory[ip] == '[') { loopCount if (loopCount == 0) { return; } } ip } if (ip == -1) { throw new RuntimeException("Unable to find a matching '['."); } } public static void main(String[] args) { Interpreter interpreter = new Interpreter(); interpreter.execute(">++++++++[-<+++++++++>]<.>>+>-[+]++>++>+++[>[->+++<<+++>]<<]> } }
881Execute Brain****
8haskell
mgiyf
import os exit_code = os.system('ls') output = os.popen('ls').read()
879Execute a system command
3python
7w2rm
import java.util.* val target = "METHINKS IT IS LIKE A WEASEL" val validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " val random = Random() fun randomChar() = validChars[random.nextInt(validChars.length)] fun hammingDistance(s1: String, s2: String) = s1.zip(s2).map { if (it.first == it.second) 0 else 1 }.sum() fun fitness(s1: String) = target.length - hammingDistance(s1, target) fun mutate(s1: String, mutationRate: Double) = s1.map { if (random.nextDouble() > mutationRate) it else randomChar() } .joinToString(separator = "") fun main(args: Array<String>) { val initialString = (0 until target.length).map { randomChar() }.joinToString(separator = "") println(initialString) println(mutate(initialString, 0.2)) val mutationRate = 0.05 val childrenPerGen = 50 var i = 0 var currVal = initialString while (currVal != target) { i += 1 currVal = (0..childrenPerGen).map { mutate(currVal, mutationRate) }.maxBy { fitness(it) }!! } println("Evolution found target after $i generations") }
880Evolutionary algorithm
11kotlin
flqdo
enum MyException: ErrorType { case TerribleException }
878Exceptions
17swift
7wvrq
system("ls") output=system("ls",intern=TRUE)
879Execute a system command
13r
5pmuy
import java.io.IOException; public class Interpreter { public final static int MEMORY_SIZE = 65536; private final char[] memory = new char[MEMORY_SIZE]; private int dp; private int ip; private int border; private void reset() { for (int i = 0; i < MEMORY_SIZE; i++) { memory[i] = 0; } ip = 0; dp = 0; } private void load(String program) { if (program.length() > MEMORY_SIZE - 2) { throw new RuntimeException("Not enough memory."); } reset(); for (; dp < program.length(); dp++) { memory[dp] = program.charAt(dp); }
881Execute Brain****
9java
flxdv
local target = "METHINKS IT IS LIKE A WEASEL" local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " local c, p = 100, 0.06 local function fitness(s) local score = #target for i = 1,#target do if s:sub(i,i) == target:sub(i,i) then score = score - 1 end end return score end local function mutate(s, rate) local result, idx = "" for i = 1,#s do if math.random() < rate then idx = math.random(#alphabet) result = result .. alphabet:sub(idx,idx) else result = result .. s:sub(i,i) end end return result, fitness(result) end local function randomString(len) local result, idx = "" for i = 1,len do idx = math.random(#alphabet) result = result .. alphabet:sub(idx,idx) end return result end local function printStep(step, s, fit) print(string.format("%04d: ", step) .. s .. " [" .. fit .."]") end math.randomseed(os.time()) local parent = randomString(#target) printStep(0, parent, fitness(parent)) local step = 0 while parent ~= target do local bestFitness, bestChild, child, fitness = #target + 1 for i = 1,c do child, fitness = mutate(parent, p) if fitness < bestFitness then bestFitness, bestChild = fitness, child end end parent, step = bestChild, step + 1 printStep(step, parent, bestFitness) end
880Evolutionary algorithm
1lua
t2sfn
function execute(code) { var mem = new Array(30000); var sp = 10000; var opcode = new String(code); var oplen = opcode.length; var ip = 0; var loopstack = new Array(); var output = ""; for (var i = 0; i < 30000; ++i) mem[i] = 0; while (ip < oplen) { switch(opcode[ip]) { case '+': mem[sp]++; break; case '-': mem[sp]--; break; case '>': sp++; break; case '<': sp--; break; case '.': if (mem[sp] != 10 && mem[sp] != 13) { output = output + Util.fromCharCode(mem[sp]); } else { puts(output); output = ""; } break; case ',': var s = console.input(); if (!s) exit(0); mem[sp] = s.charCodeAt(0); break; case '[': if (mem[sp]) { loopstack.push(ip); } else { for (var k = ip, j = 0; k < oplen; k++) { opcode[k] == '[' && j++; opcode[k] == ']' && j--; if (j == 0) break; } if (j == 0) ip = k; else { puts("Unmatched loop"); return false; } } break; case ']': ip = loopstack.pop() - 1; break; default: break; } ip++; } return true; }; if (Interp.conf('unitTest') > 0) execute(' ++++++++++[>+>+++>++++>+++++++ >++++++++>+++++++++>++++++++++>+++++++++ ++>++++++++++++<<<<<<<<<-]>>>>+.>>>>+..<.<++++++++.>>>+.<<+.<<<<++++.<+ +.>>>+++++++.>>>.+++.<+++++++.--------.<<<<<+.<+++.---. ');
881Execute Brain****
10javascript
y4o6r
string = `ls` string = %x{ls} system print `ls` exec io = IO.popen('ls') io.each {|line| puts line}
879Execute a system command
14ruby
hqujx
use std::process::Command; fn main() { let output = Command::new("ls").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); println!("{}", String::from_utf8_lossy(&output.stdout)); }
879Execute a system command
15rust
ks5h5
import scala.sys.process.Process Process("ls", Seq("-oa"))!
879Execute a system command
16scala
1orpf
(defn factorial [x] (apply * (range 2 (inc x))))
882Factorial
6clojure
3uszr
null
881Execute Brain****
11kotlin
86p0q
local funs = { ['>'] = 'ptr = ptr + 1; ', ['<'] = 'ptr = ptr - 1; ', ['+'] = 'mem[ptr] = mem[ptr] + 1; ', ['-'] = 'mem[ptr] = mem[ptr] - 1; ', ['['] = 'while mem[ptr] ~= 0 do ', [']'] = 'end; ', ['.'] = 'io.write(string.char(mem[ptr])); ', [','] = 'mem[ptr] = (io.read(1) or "\\0"):byte(); ', } local prog = [[ local mem = setmetatable({}, { __index = function() return 0 end}) local ptr = 1 ]] local source = io.read('*all') for p = 1, #source do local snippet = funs[source:sub(p,p)] if snippet then prog = prog .. snippet end end load(prog)()
881Execute Brain****
1lua
oy18h
int fact(int n) { if(n<0) { throw new IllegalArgumentException('Argument less than 0'); } return n==0? 1: n*fact(n-1); } main() { print(fact(10)); print(fact(-1)); }
882Factorial
18dart
qtjxo
use List::Util 'reduce'; use List::MoreUtils 'false'; sub randElm {$_[int rand @_]} sub minBy (&@) {my $f = shift; reduce {$f->($b) < $f->($a) ? $b : $a} @_;} sub zip {@_ or return (); for (my ($n, @a) = 0 ;; ++$n) {my @row; foreach (@_) {$n < @$_ or return @a; push @row, $_->[$n];} push @a, \@row;}} my $C = 100; my $mutation_rate = .05; my @target = split '', 'METHINKS IT IS LIKE A WEASEL'; my @valid_chars = (' ', 'A' .. 'Z'); sub fitness {false {$_->[0] eq $_->[1]} zip shift, \@target;} sub mutate {my $rate = shift; return [map {rand() < $rate ? randElm @valid_chars : $_} @{shift()}];} my $parent = [map {randElm @valid_chars} @target]; while (fitness $parent) {$parent = minBy \&fitness, map {mutate $mutation_rate, $parent} 1 .. $C; print @$parent, "\n";}
880Evolutionary algorithm
2perl
hqvjl
define('TARGET','METHINKS IT IS LIKE A WEASEL'); define('TBL','ABCDEFGHIJKLMNOPQRSTUVWXYZ '); define('MUTATE',15); define('COPIES',30); define('TARGET_COUNT',strlen(TARGET)); define('TBL_COUNT',strlen(TBL)); function unfitness($a,$b) { $sum=0; for($i=0;$i<strlen($a);$i++) if($a[$i]!=$b[$i]) $sum++; return($sum); } function mutate($a) { $tbl=TBL; for($i=0;$i<strlen($a);$i++) $out[$i]=mt_rand(0,MUTATE)?$a[$i]:$tbl[mt_rand(0,TBL_COUNT-1)]; return(implode('',$out)); } $tbl=TBL; for($i=0;$i<TARGET_COUNT;$i++) $tspec[$i]=$tbl[mt_rand(0,TBL_COUNT-1)]; $parent[0]=implode('',$tspec); $best=TARGET_COUNT+1; $iters=0; do { for($i=1;$i<COPIES;$i++) $parent[$i]=mutate($parent[0]); for($best_i=$i=0; $i<COPIES;$i++) { $unfit=unfitness(TARGET,$parent[$i]); if($unfit < $best || !$i) { $best=$unfit; $best_i=$i; } } if($best_i>0) $parent[0]=$parent[$best_i]; $iters++; print(); } while($best);
880Evolutionary algorithm
12php
zv0t1
my %code = split ' ', <<'END'; > $ptr++ < $ptr-- + $memory[$ptr]++ - $memory[$ptr]-- , $memory[$ptr]=ord(getc) . print(chr($memory[$ptr])) [ while($memory[$ptr]){ ] } END my ($ptr, @memory) = 0; eval join ';', map @code{ /./g }, <>;
881Execute Brain****
2perl
41y5d
<?php function brainfuck_interpret(&$s, &$_s, &$d, &$_d, &$i, &$_i, &$o) { do { switch($s[$_s]) { case '+': $d[$_d] = chr(ord($d[$_d]) + 1); break; case '-': $d[$_d] = chr(ord($d[$_d]) - 1); break; case '>': $_d++; if(!isset($d[$_d])) $d[$_d] = chr(0); break; case '<': $_d--; break; case '.': $o .= $d[$_d]; break; case ',': $d[$_d] = $_i==strlen($i)? chr(0) : $i[$_i++]; break; case '[': if((int)ord($d[$_d]) == 0) { $brackets = 1; while($brackets && $_s++ < strlen($s)) { if($s[$_s] == '[') $brackets++; else if($s[$_s] == ']') $brackets--; } } else { $pos = $_s++-1; if(brainfuck_interpret($s, $_s, $d, $_d, $i, $_i, $o)) $_s = $pos; } break; case ']': return ((int)ord($d[$_d]) != 0); } } while(++$_s < strlen($s)); } function brainfuck($source, $input='') { $data = array(); $data[0] = chr(0); $data_index = 0; $source_index = 0; $input_index = 0; $output = ''; brainfuck_interpret($source, $source_index, $data, $data_index, $input, $input_index, $output); return $output; } $code = ; $inp = '123'; print brainfuck( $code, $inp );
881Execute Brain****
12php
imaov
from string import letters from random import choice, random target = list() charset = letters + ' ' parent = [choice(charset) for _ in range(len(target))] minmutaterate = .09 C = range(100) perfectfitness = float(len(target)) def fitness(trial): 'Sum of matching chars by position' return sum(t==h for t,h in zip(trial, target)) def mutaterate(): 'Less mutation the closer the fit of the parent' return 1-((perfectfitness - fitness(parent)) / perfectfitness * (1 - minmutaterate)) def mutate(parent, rate): return [(ch if random() <= rate else choice(charset)) for ch in parent] def que(): '(from the favourite saying of Manuel in Fawlty Towers)' print (% (iterations, fitness(parent)*100./perfectfitness, ''.join(parent))) def mate(a, b): place = 0 if choice(xrange(10)) < 7: place = choice(xrange(len(target))) else: return a, b return a, b, a[:place] + b[place:], b[:place] + a[place:] iterations = 0 center = len(C)/2 while parent != target: rate = mutaterate() iterations += 1 if iterations% 100 == 0: que() copies = [ mutate(parent, rate) for _ in C ] + [parent] parent1 = max(copies[:center], key=fitness) parent2 = max(copies[center:], key=fitness) parent = max(mate(parent1, parent2), key=fitness) que()
880Evolutionary algorithm
3python
ksuhf
set.seed(1234, kind="Mersenne-Twister") target <- unlist(strsplit("METHINKS IT IS LIKE A WEASEL", "")) charset <- c(LETTERS, " ") parent <- sample(charset, length(target), replace=TRUE) mutaterate <- 0.01 C <- 100 fitness <- function(parent, target) { sum(parent == target) / length(target) } mutate <- function(parent, rate, charset) { p <- runif(length(parent)) nMutants <- sum(p < rate) if (nMutants) { parent[ p < rate ] <- sample(charset, nMutants, replace=TRUE) } parent } evolve <- function(parent, mutate, fitness, C, mutaterate, charset) { children <- replicate(C, mutate(parent, mutaterate, charset), simplify=FALSE) children <- c(list(parent), children) children[[which.max(sapply(children, fitness, target=target))]] } .printGen <- function(parent, target, gen) { cat(format(i, width=3), formatC(fitness(parent, target), digits=2, format="f"), paste(parent, collapse=""), "\n") } i <- 0 .printGen(parent, target, i) while (! all(parent == target)) { i <- i + 1 parent <- evolve(parent, mutate, fitness, C, mutaterate, charset) if (i%% 20 == 0) { .printGen(parent, target, i) } } .printGen(parent, target, i)
880Evolutionary algorithm
13r
recgj
[ stack ] is switch.arg ( --> [ ) [ switch.arg put ] is switch ( x --> ) [ switch.arg release ] is otherwise ( --> ) [ switch.arg share!= iff ]else[ done otherwise ]'[ do ]done[ ] is case ( x --> ) [ dip tuck unrot poke swap ] is poketape ( [ n n --> [ n ) [ 1+ over size over = if [ dip [ 0 join ] ] ] is stepright ( [ n --> [ n ) [ dup 0 = iff [ 0 rot join swap ] else [ 1 - ] ] is stepleft ( [ n --> [ n ) [ 2dup peek 1 + poketape ] is increment ( [ n --> [ n ) [ 2dup peek 1 - poketape ] is decrement ( [ n --> [ n ) [ 2dup peek emit ] is print ( [ n --> [ n ) [ temp take dup $ = iff 0 else behead swap temp put poketape ] is getchar ( [ n --> [ n ) [ 2dup peek 0 = ] is zero ( [ n --> [ n b ) [ temp put $ swap witheach [ switch [ char > case [ $ join ] char < case [ $ join ] char + case [ $ join ] char - case [ $ join ] char . case [ $ join ] char , case [ $ join ] char [ case [ $ join ] char ] case [ $ join ] otherwise ( ignore ) ] ] 0 nested 0 rot quackery temp release 2drop ] is brainf*** ( $ $ --> )
881Execute Brain****
3python
gam4h
sub fib_iter { my $n = shift; use bigint try => "GMP,Pari"; my ($v2,$v1) = (-1,1); ($v2,$v1) = ($v1,$v2+$v1) for 0..$n; $v1; }
862Fibonacci sequence
2perl
ygr6u
function fibIter($n) { if ($n < 2) { return $n; } $fibPrev = 0; $fib = 1; foreach (range(1, $n-1) as $i) { list($fibPrev, $fib) = array($fib, $fib + $fibPrev); } return $fib; }
862Fibonacci sequence
12php
and12
@target = Charset = [, *..] COPIES = 100 def random_char; Charset.sample end def fitness(candidate) sum = 0 candidate.chars.zip(@target.chars) {|x,y| sum += (x[0].ord - y[0].ord).abs} 100.0 * Math.exp(Float(sum) / -10.0) end def mutation_rate(candidate) 1.0 - Math.exp( -(100.0 - fitness(candidate)) / 400.0) end def mutate(parent, rate) parent.each_char.collect {|ch| rand <= rate? random_char: ch}.join end def log(iteration, rate, parent) puts % [iteration, rate, fitness(parent), parent] end iteration = 0 parent = Array.new(@target.length) {random_char}.join prev = while parent!= @target iteration += 1 rate = mutation_rate(parent) if prev!= parent log(iteration, rate, parent) prev = parent end copies = [parent] + Array.new(COPIES) {mutate(parent, rate)} parent = copies.max_by {|c| fitness(c)} end log(iteration, rate, parent)
880Evolutionary algorithm
14ruby
p84bh
null
880Evolutionary algorithm
15rust
1ogpu
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::stdin; use std::num::Wrapping; fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!(, args[0]); return; } let src: Vec<char> = { let mut buf = String::new(); match File::open(&args[1]) { Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); } Err(e) => { println!(, args[1], e); return; } } buf.chars().collect() }; let debug = args.contains(&.to_owned()); let brackets: HashMap<usize, usize> = { let mut m = HashMap::new(); let mut scope_stack = Vec::new(); for (idx, ch) in src.iter().enumerate() { match ch { &'[' => { scope_stack.push(idx); } &']' => { m.insert(scope_stack.pop().unwrap(), idx); } _ => { } } } m }; let mut pc: usize = 0; let mut mem: [Wrapping<u8>;5000] = [Wrapping(0);5000]; let mut ptr: usize = 0; let mut stack: Vec<usize> = Vec::new(); let stdin_ = stdin(); let mut reader = stdin_.lock().bytes(); while pc < src.len() { let Wrapping(val) = mem[ptr]; if debug { println!(, pc, ptr, val, stack.len(), src[pc]); } const ONE: Wrapping<u8> = Wrapping(1); match src[pc] { '>' => { ptr += 1; } '<' => { ptr -= 1; } '+' => { mem[ptr] = mem[ptr] + ONE; } '-' => { mem[ptr] = mem[ptr] - ONE; } '[' => { if val == 0 { pc = brackets[&pc]; } else { stack.push(pc); } } ']' => { let matching_bracket = stack.pop().unwrap(); if val!= 0 { pc = matching_bracket - 1; } } '.' => { if debug { println!(, val as char); } else { print!(, val as char); } } ',' => { mem[ptr] = Wrapping(reader.next().unwrap().unwrap()); } _ => { } } pc += 1; } }
881Execute Brain****
14ruby
7wcri
import scala.annotation.tailrec case class LearnerParams(target:String,rate:Double,C:Int) val chars = ('A' to 'Z') ++ List(' ') val randgen = new scala.util.Random def randchar = { val charnum = randgen.nextInt(chars.size) chars(charnum) } class RichTraversable[T](t: Traversable[T]) { def maxBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.max(ord on fn) def minBy[B](fn: T => B)(implicit ord: Ordering[B]) = t.min(ord on fn) } implicit def toRichTraversable[T](t: Traversable[T]) = new RichTraversable(t) def fitness(candidate:String)(implicit params:LearnerParams) = (candidate zip params.target).map { case (a,b) => if (a==b) 1 else 0 }.sum def mutate(initial:String)(implicit params:LearnerParams) = initial.map{ samechar => if(randgen.nextDouble < params.rate) randchar else samechar } @tailrec def evolve(generation:Int, initial:String)(implicit params:LearnerParams){ import params._ printf("Generation:%3d %s\n",generation, initial) if(initial == target) return () val candidates = for (number <- 1 to C) yield mutate(initial) val next = candidates.maxBy(fitness) evolve(generation+1,next) } implicit val params = LearnerParams("METHINKS IT IS LIKE A WEASEL",0.01,100) val initial = (1 to params.target.size) map(x => randchar) mkString evolve(0,initial)
880Evolutionary algorithm
16scala
wdjes
use std::collections::HashMap; use std::env; use std::fs::File; use std::io::prelude::*; use std::io::stdin; use std::num::Wrapping; fn main() { let args: Vec<_> = env::args().collect(); if args.len() < 2 { println!("Usage: {} [path] (--debug)", args[0]); return; } let src: Vec<char> = { let mut buf = String::new(); match File::open(&args[1]) { Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); } Err(e) => { println!("Error opening '{}': {}", args[1], e); return; } } buf.chars().collect() };
881Execute Brain****
15rust
jxl72
import scala.annotation._ trait Func[T] { val zero: T def inc(t: T): T def dec(t: T): T def in: T def out(t: T): Unit } object ByteFunc extends Func[Byte] { override val zero: Byte = 0 override def inc(t: Byte) = ((t + 1) & 0xFF).toByte override def dec(t: Byte) = ((t - 1) & 0xFF).toByte override def in: Byte = readByte override def out(t: Byte) { print(t.toChar) } } case class Tape[T](left: List[T], cell: T, right: List[T])(implicit func: Func[T]) { private def headOf(list:List[T]) = if (list.isEmpty) func.zero else list.head private def tailOf(list:List[T]) = if (list.isEmpty) Nil else list.tail def isZero = cell == func.zero def execute(ch: Char) = (ch: @switch) match { case '+' => copy(cell = func.inc(cell)) case '-' => copy(cell = func.dec(cell)) case '<' => Tape(tailOf(left), headOf(left), cell :: right) case '>' => Tape(cell :: left, headOf(right), tailOf(right)) case '.' => func.out(cell); this case ',' => copy(cell = func.in) case '[' | ']' => this case _ => error("Unexpected token: " + ch) } } object Tape { def empty[T](func: Func[T]) = Tape(Nil, func.zero, Nil)(func) } class Brainfuck[T](func:Func[T]) { def execute(p: String) { val prog = p.replaceAll("[^\\+\\-\\[\\]\\.\\,\\>\\<]", "") @tailrec def braceMatcher(pos: Int, stack: List[Int], o2c: Map[Int, Int]): Map[Int,Int] = if(pos == prog.length) o2c else (prog(pos): @switch) match { case '[' => braceMatcher(pos + 1, pos :: stack, o2c) case ']' => braceMatcher(pos + 1, stack.tail, o2c + (stack.head -> pos)) case _ => braceMatcher(pos + 1, stack, o2c) } val open2close = braceMatcher(0, Nil, Map()) val close2open = open2close.map(_.swap) @tailrec def ex(pos:Int, tape:Tape[T]): Unit = if(pos < prog.length) ex((prog(pos): @switch) match { case '[' if tape.isZero => open2close(pos) case ']' if ! tape.isZero => close2open(pos) case _ => pos + 1 }, tape.execute(prog(pos))) println("---running---") ex(0, Tape.empty(func)) println("\n---done---") } }
881Execute Brain****
16scala
b0uk6
import Foundation let valids = [">", "<", "+", "-", ".", ",", "[", "]"] as Set<Character> var ip = 0 var dp = 0 var data = [UInt8](count: 30_000, repeatedValue: 0) let input = Process.arguments if input.count!= 2 { fatalError("Need one input file") } let infile: String! do { infile = try String(contentsOfFile: input[1], encoding: NSUTF8StringEncoding)?? "" } catch let err { infile = "" } var program = ""
881Execute Brain****
17swift
re9gg
func evolve( to target: String, parent: inout String, mutationRate: Int, copies: Int ) { var parentFitness: Int { return fitness(target: target, sentence: parent) } var generation = 0 while parent!= target { generation += 1 let bestOfGeneration = (0..<copies) .map({_ in mutate(sentence: parent, rate: mutationRate) }) .map({ (fitness(target: target, sentence: $0), $0) }) .sorted(by: { $0.0 < $1.0 }) .first! if bestOfGeneration.0 < parentFitness { print("Gen \(generation) produced better fit. \(bestOfGeneration.1) with fitness \(bestOfGeneration.0)") parent = bestOfGeneration.1 } } } func fitness(target: String, sentence: String) -> Int { return zip(target, sentence).filter(!=).count } func mutate(sentence: String, rate: Int) -> String { return String( sentence.map({char in if Int.random(in: 1...100) - rate <= 0 { return "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".randomElement()! } else { return char } }) ) } let target = "METHINKS IT IS LIKE A WEASEL" let copies = 100 let mutationRate = 20 var start = mutate(sentence: target, rate: 100) print("target: \(target)") print("Gen 0: \(start) with fitness \(fitness(target: target, sentence: start))") evolve(to: target, parent: &start, mutationRate: mutationRate, copies: 100)
880Evolutionary algorithm
17swift
b05kd
from math import * def analytic_fibonacci(n): sqrt_5 = sqrt(5); p = (1 + sqrt_5) / 2; q = 1/p; return int( (p**n + q**n) / sqrt_5 + 0.5 ) for i in range(1,31): print analytic_fibonacci(i),
862Fibonacci sequence
3python
mr7yh
fib=function(n,x=c(0,1)) { if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x)) if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0) } sapply(seq(-31,31),fib)
862Fibonacci sequence
13r
zu5th
package main import ( "fmt" "math/big" ) func main() { fmt.Println(factorial(800)) } func factorial(n int64) *big.Int { if n < 0 { return nil } r := big.NewInt(1) var f big.Int for i := int64(2); i <= n; i++ { r.Mul(r, f.SetInt64(i)) } return r }
882Factorial
0go
remgm
def rFact rFact = { (it > 1) ? it * rFact(it - 1): 1 as BigInteger }
882Factorial
7groovy
vkt28
factorial n = product [1..n]
882Factorial
8haskell
03ks7
def fib(n) if n < 2 n else prev, fib = 0, 1 (n-1).times do prev, fib = fib, fib + prev end fib end end p (0..10).map { |i| fib(i) }
862Fibonacci sequence
14ruby
cjh9k
int main(void) { double a, b, h, n2, r, u, v; int k, k2, m, n; printf(); n = 400; h = 1; for (k = 2; k <= n; k++) { h += 1.0 / k; } a = log(n +.5 + 1.0 / (24*n)); printf(, h); printf(, h - a, n); printf(); n = 21; double s[] = {0, n}; r = n; k = 1; do { k += 1; r *= (double) n / k; s[k & 1] += r / k; } while (r > eps); printf(, s[1] - s[0] - log(n), k); printf(); n = 5; a = 1; h = 1; n2 = pow(2,n); r = 1; k = 1; do { k += 1; r *= n2 / k; h += 1.0 / k; b = a; a += r * h; } while (fabs(b - a) > eps); a *= n2 / exp(n2); printf(, a - n * log(2), k); printf(); n = 13; a = -log(n); b = 1; u = a; v = b; n2 = n * n; k2 = 0; k = 0; do { k2 += 2*k + 1; k += 1; a *= n2 / k; b *= n2 / k2; a = (a + b) / k; u += a; v += b; } while (fabs(a) > eps); printf(, u / v, k); printf(); double B2[] = {1.0,1.0/6,-1.0/30,1.0/42,-1.0/30,\ 5.0/66,-691.0/2730,7.0/6,-3617.0/510,43867.0/798}; m = 7; if (m > 9) return(0); n = 10; h = 1; for (k = 2; k <= n; k++) { h += 1.0 / k; } printf(, h); h -= log(n); printf(, h); a = -1.0 / (2*n); n2 = n * n; r = 1; for (k = 1; k <= m; k++) { r *= n2; a += B2[k] / (2*k * r); } printf(, a, h + a, n + m); printf(); }
883Euler's constant 0.5772...
5c
jx970
fn main() { let mut prev = 0;
862Fibonacci sequence
15rust
lhkcc
use strict; use warnings; use List::Util qw( sum ); print sum( map 1 / $_, 1 .. 1e6) - log 1e6, "\n";
883Euler's constant 0.5772...
2perl
p8vb0
def fib(i: Int): Int = i match { case 0 => 0 case 1 => 1 case _ => fib(i - 1) + fib(i - 2) }
862Fibonacci sequence
16scala
up1v8
n = 1e6 p (1..n).sum{ 1.0/_1 } - Math.log(n)
883Euler's constant 0.5772...
14ruby
en4ax
null
883Euler's constant 0.5772...
15rust
wdge4
package programas; import java.math.BigInteger; import java.util.InputMismatchException; import java.util.Scanner; public class IterativeFactorial { public BigInteger factorial(BigInteger n) { if ( n == null ) { throw new IllegalArgumentException(); } else if ( n.signum() == - 1 ) {
882Factorial
9java
ai41y
function factorial(n) {
882Factorial
10javascript
szhqz
int main() { wchar_t pi = L'\u03c0'; wchar_t ae = L'\u2245'; double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ); printf(, pi, creal(e), cimag(e), ae); return 0; }
884Euler's identity
5c
aiu11
package main import ( "fmt" "math" "math/cmplx" ) func main() { fmt.Println(cmplx.Exp(math.Pi * 1i) + 1.0) }
884Euler's identity
0go
mg0yi
import static Complex.* Number.metaClass.mixin ComplexCategory def = Math.PI def e = Math.E println "e ** ( * i) + 1 = " + (e ** ( * i) + 1) println "| e ** ( * i) + 1 | = " + (e ** ( * i) + 1).
884Euler's identity
7groovy
t2efh
fun facti(n: Int) = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") else -> { var ans = 1L for (i in 2..n) ans *= i ans } } fun factr(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("negative numbers not allowed") n < 2 -> 1L else -> n * factr(n - 1) } fun main(args: Array<String>) { val n = 20 println("$n! = " + facti(n)) println("$n! = " + factr(n)) }
882Factorial
11kotlin
hqlj3
import Data.Complex eulerIdentityZeroIsh :: Complex Double eulerIdentityZeroIsh = exp (0:+ pi) + 1 main :: IO () main = print eulerIdentityZeroIsh
884Euler's identity
8haskell
ksch0
public class EulerIdentity { public static void main(String[] args) { System.out.println("e ^ (i*Pi) + 1 = " + (new Complex(0, Math.PI).exp()).add(new Complex(1, 0))); } public static class Complex { private double x, y; public Complex(double re, double im) { x = re; y = im; } public Complex exp() { double exp = Math.exp(x); return new Complex(exp * Math.cos(y), exp * Math.sin(y)); } public Complex add(Complex a) { return new Complex(x + a.x, y + a.y); } @Override public String toString() { return x + " + " + y + "i"; } } }
884Euler's identity
9java
41z58
null
884Euler's identity
11kotlin
ljicp
SELECT round ( EXP ( SUM (ln ( ( 1 + SQRT( 5 ) ) / 2) ) OVER ( ORDER BY level ) ) / SQRT( 5 ) ) fibo FROM dual CONNECT BY level <= 10;
862Fibonacci sequence
19sql
gew4k
local c = { new = function(s,r,i) s.__index=s return setmetatable({r=r, i=i}, s) end, add = function(s,o) return s:new(s.r+o.r, s.i+o.i) end, exp = function(s) local e=math.exp(s.r) return s:new(e*math.cos(s.i), e*math.sin(s.i)) end, mul = function(s,o) return s:new(s.r*o.r+s.i*o.i, s.r*o.i+s.i*o.r) end } local i = c:new(0, 1) local pi = c:new(math.pi, 0) local one = c:new(1, 0) local zero = i:mul(pi):exp():add(one) print(string.format("e^(i*pi)+1 is approximately zero: %.18g%+.18gi", zero.r, zero.i))
884Euler's identity
1lua
2hnl3
use Math::Complex; print exp(pi * i) + 1, "\n";
884Euler's identity
2perl
qtrx6
>>> import math >>> math.e ** (math.pi * 1j) + 1 1.2246467991473532e-16j
884Euler's identity
3python
sz7q9
exp(1i * pi) + 1
884Euler's identity
13r
en5ad
import Cocoa func fibonacci(n: Int) -> Int { let square_root_of_5 = sqrt(5.0) let p = (1 + square_root_of_5) / 2 let q = 1 / p return Int((pow(p,CDouble(n)) + pow(q,CDouble(n))) / square_root_of_5 + 0.5) } for i in 1...30 { println(fibonacci(i)) }
862Fibonacci sequence
17swift
97jmj
include Math E ** (PI * 1i) + 1
884Euler's identity
14ruby
86h01
use std::f64::consts::PI; extern crate num_complex; use num_complex::Complex; fn main() { println!("{:e}", Complex::new(0.0, PI).exp() + 1.0); }
884Euler's identity
15rust
oyk83
import spire.math.{Complex, Real} object Scratch extends App{
884Euler's identity
16scala
dc1ng
package main import ( "fmt" "math" "rcu" ) var limit = int(math.Log(1e6) * 1e6 * 1.2)
885Erdös-Selfridge categorization of primes
0go
gaz4n
typedef double (*deriv_f)(double, double); void ivp_euler(deriv_f f, double y, int step, int end_t) { int t = 0; printf(, (int)step); do { if (t % 10 == 0) printf(FMT, y); y += step * f(t, y); } while ((t += step) <= end_t); printf(); } void analytic() { double t; printf(); for (t = 0; t <= 100; t += 10) printf(, t); printf(); for (t = 0; t <= 100; t += 10) printf(FMT, 20 + 80 * exp(-0.07 * t)); printf(); } double cooling(double t, double temp) { return -0.07 * (temp - 20); } int main() { analytic(); ivp_euler(cooling, 100, 2, 100); ivp_euler(cooling, 100, 5, 100); ivp_euler(cooling, 100, 10, 100); return 0; }
886Euler method
5c
vki2o
import java.util.*; public class ErdosSelfridge { private int[] primes; private int[] category; public static void main(String[] args) { ErdosSelfridge es = new ErdosSelfridge(1000000); System.out.println("First 200 primes:"); for (var e : es.getPrimesByCategory(200).entrySet()) { int category = e.getKey(); List<Integer> primes = e.getValue(); System.out.printf("Category%d:\n", category); for (int i = 0, n = primes.size(); i != n; ++i) System.out.printf("%4d%c", primes.get(i), (i + 1) % 15 == 0 ? '\n' : ' '); System.out.printf("\n\n"); } System.out.println("First 1,000,000 primes:"); for (var e : es.getPrimesByCategory(1000000).entrySet()) { int category = e.getKey(); List<Integer> primes = e.getValue(); System.out.printf("Category%2d: first =%7d last =%8d count =%d\n", category, primes.get(0), primes.get(primes.size() - 1), primes.size()); } } private ErdosSelfridge(int limit) { PrimeGenerator primeGen = new PrimeGenerator(100000, 200000); List<Integer> primeList = new ArrayList<>(); for (int i = 0; i < limit; ++i) primeList.add(primeGen.nextPrime()); primes = new int[primeList.size()]; for (int i = 0; i < primes.length; ++i) primes[i] = primeList.get(i); category = new int[primes.length]; } private Map<Integer, List<Integer>> getPrimesByCategory(int limit) { Map<Integer, List<Integer>> result = new TreeMap<>(); for (int i = 0; i < limit; ++i) { var p = result.computeIfAbsent(getCategory(i), k -> new ArrayList<Integer>()); p.add(primes[i]); } return result; } private int getCategory(int index) { if (category[index] != 0) return category[index]; int maxCategory = 0; int n = primes[index] + 1; for (int i = 0; n > 1; ++i) { int p = primes[i]; if (p * p > n) break; int count = 0; for (; n % p == 0; ++count) n /= p; if (count != 0) { int category = (p <= 3) ? 1 : 1 + getCategory(i); maxCategory = Math.max(maxCategory, category); } } if (n > 1) { int category = (n <= 3) ? 1 : 1 + getCategory(getIndex(n)); maxCategory = Math.max(maxCategory, category); } category[index] = maxCategory; return maxCategory; } private int getIndex(int prime) { return Arrays.binarySearch(primes, prime); } }
885Erdös-Selfridge categorization of primes
9java
1o2p2
use strict; use warnings; use feature 'say'; use List::Util 'max'; use ntheory qw/factor/; use Primesieve qw(generate_primes); my @primes = (0, generate_primes (1, 10**8)); my %cat = (2 => 1, 3 => 1); sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub ES { my ($n) = @_; my @factors = factor $n + 1; my $category = max map { defined $cat{$_} and $cat{$_} } @factors; unless (defined $cat{ $factors[-1] }) { $category = max $category, (1 + max map { $cat{$_} } factor 1 + $factors[-1]); $cat{ $factors[-1] } = $category; } $category } my %es; my $upto = 200; push @{$es{ES($_)}}, $_ for @primes[1..$upto]; say "First $upto primes, Erds-Selfridge categorized:"; say "$_: " . join ' ', sort {$a <=> $b} @{$es{$_}} for sort keys %es; %es = (); $upto = 1_000_000; say "\nSummary of first @{[comma $upto]} primes, Erds-Selfridge categorized:"; push @{$es{ES($_)}}, $_ for @primes[1..$upto]; printf "Category%2d: first:%9s last:%10s count:%s\n", map { comma $_ } $_, (sort {$a <=> $b} @{$es{$_}})[0, -1], scalar @{$es{$_}} for sort {$a <=> $b} keys %es;
885Erdös-Selfridge categorization of primes
2perl
t2afg
function fact(n) return n > 0 and n * fact(n-1) or 1 end
882Factorial
1lua
ks2h2
(ns newton-cooling (:gen-class)) (defn euler [f y0 a b h] "Euler's Method. Approximates y(time) in y'(time)=f(time,y) with y(a)=y0 and t=a..b and the step size h." (loop [t a y y0 result []] (if (<= t b) (recur (+ t h) (+ y (* (f (+ t h) y) h)) (conj result [(double t) (double y)])) result))) (defn newton-coolling [t temp] "Newton's cooling law, f(t,T) = -0.07*(T-20)" (* -0.07 (- temp 20))) (println "Example output") (doseq [q (euler newton-coolling 100 0 100 10)] (println (apply format "%.3f%.3f" q)))
886Euler method
6clojure
rezg2
null
885Erdös-Selfridge categorization of primes
15rust
y4q68
typedef int bool; typedef unsigned long long ull; char as_digit(int d) { return (d >= 0 && d <= 9) ? d + '0' : d - 10 + 'a'; } void revstr(char *str) { int i, len = strlen(str); char t; for (i = 0; i < len/2; ++i) { t = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = t; } } char* to_base(char s[], ull n, int b) { int i = 0; while (n) { s[i++] = as_digit(n % b); n /= b; } s[i] = '\0'; revstr(s); return s; } ull uabs(ull a, ull b) { return a > b ? a - b : b - a; } bool is_esthetic(ull n, int b) { int i, j; if (!n) return FALSE; i = n % b; n /= b; while (n) { j = n % b; if (uabs(i, j) != 1) return FALSE; n /= b; i = j; } return TRUE; } ull esths[45000]; int le = 0; void dfs(ull n, ull m, ull i) { ull d, i1, i2; if (i >= n && i <= m) esths[le++] = i; if (i == 0 || i > m) return; d = i % 10; i1 = i * 10 + d - 1; i2 = i1 + 2; if (d == 0) { dfs(n, m, i2); } else if (d == 9) { dfs(n, m, i1); } else { dfs(n, m, i1); dfs(n, m, i2); } } void list_esths(ull n, ull n2, ull m, ull m2, int per_line, bool all) { int i; le = 0; for (i = 0; i < 10; ++i) { dfs(n2, m2, i); } printf(, le, n, m); if (all) { for (i = 0; i < le; ++i) { printf(, esths[i]); if (!(i+1)%per_line) printf(); } } else { for (i = 0; i < per_line; ++i) printf(, esths[i]); printf(); for (i = le - per_line; i < le; ++i) printf(, esths[i]); } printf(); } int main() { ull n; int b, c; char ch[15] = {0}; for (b = 2; b <= 16; ++b) { printf(, b, 4*b, 6*b); for (n = 1, c = 0; c < 6 * b; ++n) { if (is_esthetic(n, b)) { if (++c >= 4 * b) printf(, to_base(ch, n, b)); } } printf(); } char *oldLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, ); list_esths(1000, 1010, 9999, 9898, 16, TRUE); list_esths(1e8, 101010101, 13*1e7, 123456789, 9, TRUE); list_esths(1e11, 101010101010, 13*1e10, 123456789898, 7, FALSE); list_esths(1e14, 101010101010101, 13*1e13, 123456789898989, 5, FALSE); list_esths(1e17, 101010101010101010, 13*1e16, 123456789898989898, 4, FALSE); setlocale(LC_NUMERIC, oldLocale); return 0; }
887Esthetic numbers
5c
9rqm1
package main import ( "fmt" "log" "rcu" "sort" ) func ord(n int) string { if n < 0 { log.Fatal("Argument must be a non-negative integer.") } m := n % 100 if m >= 4 && m <= 20 { return fmt.Sprintf("%sth", rcu.Commatize(n)) } m %= 10 suffix := "th" if m == 1 { suffix = "st" } else if m == 2 { suffix = "nd" } else if m == 3 { suffix = "rd" } return fmt.Sprintf("%s%s", rcu.Commatize(n), suffix) } func main() { limit := int(4 * 1e8) c := rcu.PrimeSieve(limit-1, true) var compSums []int var primeSums []int csum := 0 psum := 0 for i := 2; i < limit; i++ { if c[i] { csum += i compSums = append(compSums, csum) } else { psum += i primeSums = append(primeSums, psum) } } for i := 0; i < len(primeSums); i++ { ix := sort.SearchInts(compSums, primeSums[i]) if ix < len(compSums) && compSums[ix] == primeSums[i] { cps := rcu.Commatize(primeSums[i]) fmt.Printf("%21s -%12s prime sum,%12s composite sum\n", cps, ord(i+1), ord(ix+1)) } } }
888Equal prime and composite sums
0go
aic1f
use strict; use warnings; use feature <say state>; use ntheory <is_prime next_prime>; sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r } sub suffix { my($d) = $_[0] =~ /(.)$/; $d == 1 ? 'st' : $d == 2 ? 'nd' : $d == 3 ? 'rd' : 'th' } sub prime_sum { state $s = state $p = 2; state $i = 1; if ($i < (my $n = shift) ) { do { $s += $p = next_prime($p) } until ++$i == $n } $s } sub composite_sum { state $s = state $c = 4; state $i = 1; if ($i < (my $n = shift) ) { do { 1 until ! is_prime(++$c); $s += $c } until ++$i == $n } $s } my $ci++; for my $pi (1 .. 5_012_372) { next if prime_sum($pi) < composite_sum($ci); printf( "%20s -%11s prime sum,%12s composite sum\n", comma(prime_sum $pi), comma($pi).suffix($pi), comma($ci).suffix($ci)) and next if prime_sum($pi) == composite_sum($ci); $ci++; redo }
888Equal prime and composite sums
2perl
2h0lf
package main import ( "fmt" "math" )
886Euler method
0go
szgqa
package main import ( "fmt" "strconv" ) func uabs(a, b uint64) uint64 { if a > b { return a - b } return b - a } func isEsthetic(n, b uint64) bool { if n == 0 { return false } i := n % b n /= b for n > 0 { j := n % b if uabs(i, j) != 1 { return false } n /= b i = j } return true } var esths []uint64 func dfs(n, m, i uint64) { if i >= n && i <= m { esths = append(esths, i) } if i == 0 || i > m { return } d := i % 10 i1 := i*10 + d - 1 i2 := i1 + 2 if d == 0 { dfs(n, m, i2) } else if d == 9 { dfs(n, m, i1) } else { dfs(n, m, i1) dfs(n, m, i2) } } func listEsths(n, n2, m, m2 uint64, perLine int, all bool) { esths = esths[:0] for i := uint64(0); i < 10; i++ { dfs(n2, m2, i) } le := len(esths) fmt.Printf("Base 10:%s esthetic numbers between%s and%s:\n", commatize(uint64(le)), commatize(n), commatize(m)) if all { for c, esth := range esths { fmt.Printf("%d ", esth) if (c+1)%perLine == 0 { fmt.Println() } } } else { for i := 0; i < perLine; i++ { fmt.Printf("%d ", esths[i]) } fmt.Println("\n............\n") for i := le - perLine; i < le; i++ { fmt.Printf("%d ", esths[i]) } } fmt.Println("\n") } func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { for b := uint64(2); b <= 16; b++ { fmt.Printf("Base%d:%dth to%dth esthetic numbers:\n", b, 4*b, 6*b) for n, c := uint64(1), uint64(0); c < 6*b; n++ { if isEsthetic(n, b) { c++ if c >= 4*b { fmt.Printf("%s ", strconv.FormatUint(n, int(b))) } } } fmt.Println("\n") }
887Esthetic numbers
0go
en2a6
def eulerStep = { xn, yn, h, dydx -> (yn + h * dydx(xn, yn)) as BigDecimal } Map eulerMapping = { x0, y0, h, dydx, stopCond = { xx, yy, hh, xx0 -> abs(xx - xx0) > (hh * 100) }.rcurry(h, x0) -> Map yMap = [:] yMap[x0] = y0 as BigDecimal def x = x0 while (!stopCond(x, yMap[x])) { yMap[x + h] = eulerStep(x, yMap[x], h, dydx) x += h } yMap } assert eulerMapping.maximumNumberOfParameters == 5
886Euler method
7groovy
ai21p