code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
public class Tree<T>{ private T value; private Tree<T> left; private Tree<T> right; public void replaceAll(T value){ this.value = value; if (left != null) left.replaceAll(value); if (right != null) right.replaceAll(value); } }
470Parametric polymorphism
9java
nhrih
def fs = { fn, values -> values.collect { fn(it) } } def f1 = { v -> v * 2 } def f2 = { v -> v ** 2 } def fsf1 = fs.curry(f1) def fsf2 = fs.curry(f2)
468Partial function application
7groovy
dkhn3
fs = map f1 = (* 2) f2 = (^ 2) fsf1 = fs f1 fsf2 = fs f2 main :: IO () main = do print $ fsf1 [0, 1, 2, 3] print $ fsf2 [0, 1, 2, 3] print $ fsf1 [2, 4, 6, 8] print $ fsf2 [2, 4, 6, 8]
468Partial function application
8haskell
j3z7g
function randPW (length) local index, pw, rnd = 0, "" local chars = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" } repeat index = index + 1 rnd = math.random(chars[index]:len()) if math.random(2) == 1 then pw = pw .. chars[index]:sub(rnd, rnd) else pw = chars[index]:sub(rnd, rnd) .. pw end index = index % #chars until pw:len() >= length return pw end math.randomseed(os.time()) if #arg ~= 2 then print("\npwgen.lua") print("=========\n") print("A Lua script to generate random passwords.\n") print("Usage: lua pwgen.lua [password length] [number of passwords to generate]\n") os.exit() end for i = 1, arg[2] do print(randPW(tonumber(arg[1]))) end
463Password generator
1lua
gf64j
void die(const char *msg) { fprintf(stderr, , msg); abort(); } double stack[MAX_D]; int depth; void push(double v) { if (depth >= MAX_D) die(); stack[depth++] = v; } double pop() { if (!depth) die(); return stack[--depth]; } double rpn(char *s) { double a, b; int i; char *e, *w = ; for (s = strtok(s, w); s; s = strtok(0, w)) { a = strtod(s, &e); if (e > s) printf(), push(a); else if (*s == '+') binop(a + b); else if (*s == '-') binop(a - b); else if (*s == '*') binop(a * b); else if (*s == '/') binop(a / b); else if (*s == '^') binop(pow(a, b)); else { fprintf(stderr, , *s); die(); } for (i = depth; i-- || 0 * putchar('\n'); ) printf(, stack[i]); } if (depth != 1) die(); return pop(); } int main(void) { char s[] = ; printf(, rpn(s)); return 0; }
479Parsing/RPN calculator algorithm
5c
e2nav
import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement; public class DBDemo{ private String protocol;
475Parameterized SQL statement
9java
9qkmu
null
469Parse an IP Address
11kotlin
vo021
null
470Parametric polymorphism
11kotlin
s4vq7
from itertools import combinations as cmb def isP(n): if n == 2: return True if n% 2 == 0: return False return all(n% x > 0 for x in range(3, int(n ** 0.5) + 1, 2)) def genP(n): p = [2] p.extend([x for x in range(3, n + 1, 2) if isP(x)]) return p data = [ (99809, 1), (18, 2), (19, 3), (20, 4), (2017, 24), (22699, 1), (22699, 2), (22699, 3), (22699, 4), (40355, 3)] for n, cnt in data: ci = iter(cmb(genP(n), cnt)) while True: try: c = next(ci) if sum(c) == n: print(' '.join( [repr((n, cnt)), , '+'.join(str(s) for s in c)] )) break except StopIteration: print(repr((n, cnt)) + ) break
467Partition an integer x into n primes
3python
gff4h
extension Numeric where Self: Strideable { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } } protocol PathologicalFloat: SignedNumeric, Strideable, ExpressibleByFloatLiteral { static var e: Self { get } static func /(_ lhs: Self, _ rhs: Self) -> Self } extension Double: PathologicalFloat { static var e: Double { Double("2.71828182845904523536028747135266249")! } } extension Float: PathologicalFloat { static var e: Float { Float("2.7182818284590")! } } extension Decimal: PathologicalFloat { static var e: Decimal { Decimal(string: "2.71828182845904523536028747135266249")! } } extension BDouble: PathologicalFloat { static var e: BDouble { BDouble("2.71828182845904523536028747135266249")! } public func advanced(by n: BDouble) -> BDouble { self + n } public func distance(to other: BDouble) -> BDouble { abs(self - other) } } func badSequence<T: PathologicalFloat>(n: Int) -> T { guard n!= 1 else { return 2 } guard n!= 2 else { return -4 } var a: T = 2, b: T = -4 for _ in stride(from: 2, to: n, by: 1) { (a, b) = (b, 111 - 1130 / b + 3000 / (a * b)) } return b } func chaoticBank<T: PathologicalFloat>(years: T) -> T { var balance = T.e - 1 for year: T in stride(from: 1, through: 25, by: 1) { balance = (balance * year) - 1 } return balance } func rumpFunction<T: PathologicalFloat>(_ a: T, _ b: T) -> T { let aSquared = a.power(2) let bSix = b.power(6) let f1 = 333.75 * bSix let f2 = aSquared * (11 * aSquared * b.power(2) - bSix - 121 * b.power(4) - 2) let f3 = 5.5 * b.power(8) + a / (2 * b) return f1 + f2 + f3 } func fmt<T: CVarArg>(_ n: T) -> String { String(format: "%16.16f", n) } print("Bad sequence") for i in [3, 4, 5, 6, 7, 8, 20, 30, 50, 100] { let vFloat: Float = badSequence(n: i) let vDouble: Double = badSequence(n: i) let vDecimal: Decimal = badSequence(n: i) let vBigDouble: BDouble = badSequence(n: i) print("v(\(i)) as Float \(fmt(vFloat)); as Double = \(fmt(vDouble)); as Decimal = \(vDecimal); as BDouble = \(vBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))") } let bankFloat: Float = chaoticBank(years: 25) let bankDouble: Double = chaoticBank(years: 25) let bankDecimal: Decimal = chaoticBank(years: 25) let bankBigDouble: BDouble = chaoticBank(years: 25) print("\nChaotic bank") print("After 25 years your bank will be \(bankFloat) if stored as a Float") print("After 25 years your bank will be \(bankDouble) if stored as a Double") print("After 25 years your bank will be \(bankDecimal) if stored as a Decimal") print("After 25 years your bank will be \(bankBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false)) if stored as a BigDouble") let rumpFloat: Float = rumpFunction(77617.0, 33096.0) let rumpDouble: Double = rumpFunction(77617.0, 33096.0) let rumpDecimal: Decimal = rumpFunction(77617.0, 33096.0) let rumpBigDouble: BDouble = rumpFunction(77617.0, 33096.0) print("\nRump's function") print("rump(77617.0, 33096.0) as Float \(rumpFloat); as Double = \(rumpDouble); as Decimal = \(rumpDecimal); as BDouble = \(rumpBigDouble.decimalExpansion(precisionAfterDecimalPoint: 16, rounded: false))")
461Pathological floating point problems
17swift
p95bl
package main import "fmt" func pancake(n int) int { gap, sum, adj := 2, 2, -1 for sum < n { adj++ gap = gap*2 - 1 sum += gap } return n + adj } func main() { for i := 0; i < 4; i++ { for j := 1; j < 6; j++ { n := i*5 + j fmt.Printf("p(%2d) =%2d ", n, pancake(n)) } fmt.Println() } }
477Pancake numbers
0go
ui1vt
public class Pancake { private static int pancake(int n) { int gap = 2; int sum = 2; int adj = -1; while (sum < n) { adj++; gap = 2 * gap - 1; sum += gap; } return n + adj; } public static void main(String[] args) { for (int i = 0; i < 4; i++) { for (int j = 1; j < 6; j++) { int n = 5 * i + j; System.out.printf("p(%2d) =%2d ", n, pancake(n)); } System.out.println(); } } }
477Pancake numbers
9java
ky8hm
null
475Parameterized SQL statement
11kotlin
z1gts
sub parse_v4 { my ($ip, $port) = @_; my @quad = split(/\./, $ip); return unless @quad == 4; for (@quad) { return if ($_ > 255) } if (!length $port) { $port = -1 } elsif ($port =~ /^(\d+)$/) { $port = $1 } else { return } my $h = join '' => map(sprintf("%02x", $_), @quad); return $h, $port } sub parse_v6 { my $ip = shift; my $omits; return unless $ip =~ /^[\da-f:.]+$/i; $ip =~ s/^:/0:/; $omits = 1 if $ip =~ s/::/:z:/g; return if $ip =~ /z.*z/; my $v4 = ''; my $len = 8; if ($ip =~ s/:((?:\d+\.){3}\d+)$//) { ($v4) = parse_v4($1) or return; $len -= 2; } return unless $ip =~ /^[:a-fz\d]+$/i; my @h = split(/:/, $ip); return if @h + $omits > $len; @h = map( $_ eq 'z' ? (0) x ($len - @h + 1) : ($_), @h); return join('' => map(sprintf("%04x", hex($_)), @h)).$v4; } sub parse_ip { my $str = shift; $str =~ s/^\s*//; $str =~ s/\s*$//; if ($str =~ s/^((?:\d+\.)+\d+)(?::(\d+))?$//) { return 'v4', parse_v4($1, $2); } my ($ip, $port); if ($str =~ /^\[(.*?)\]:(\d+)$/) { $port = $2; $ip = parse_v6($1); } else { $port = -1; $ip = parse_v6($str); } return unless $ip; return 'v6', $ip, $port; } for (qw/127.0.0.1 127.0.0.1:80 ::1 [::1]:80 2605:2700:0:3::4713:93e3 [2605:2700:0:3::4713:93e3]:80 ::ffff:192.168.0.1 [::ffff:192.168.0.1]:22 ::ffff:127.0.0.0.1 a::b::1/) { print "$_\n\t"; my ($ver, $ip, $port) = parse_ip($_) or print "parse error\n" and next; print "$ver $ip\tport $port\n\n"; }
469Parse an IP Address
2perl
0g5s4
package main import ( "fmt" "strings" ) var tests = []string{ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^", } var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } const nPrec = 9 func main() { for _, t := range tests { parseRPN(t) } } func parseRPN(e string) { fmt.Println("\npostfix:", e) type sf struct { prec int expr string } var stack []sf for _, tok := range strings.Fields(e) { fmt.Println("token:", tok) if op, isOp := opa[tok]; isOp { rhs := &stack[len(stack)-1] stack = stack[:len(stack)-1] lhs := &stack[len(stack)-1] if lhs.prec < op.prec || (lhs.prec == op.prec && op.rAssoc) { lhs.expr = "(" + lhs.expr + ")" } lhs.expr += " " + tok + " " if rhs.prec < op.prec || (rhs.prec == op.prec && !op.rAssoc) { lhs.expr += "(" + rhs.expr + ")" } else { lhs.expr += rhs.expr } lhs.prec = op.prec } else { stack = append(stack, sf{nPrec, tok}) } for _, f := range stack { fmt.Printf(" %d%q\n", f.prec, f.expr) } } fmt.Println("infix:", stack[0].expr) }
472Parsing/RPN to infix conversion
0go
kyfhz
import java.util.Arrays; public class PartialApplication { interface IntegerFunction { int call(int arg); }
468Partial function application
9java
uiovv
fun pancake(n: Int): Int { var gap = 2 var sum = 2 var adj = -1 while (sum < n) { adj++ gap = gap * 2 - 1 sum += gap } return n + adj } fun main() { (1 .. 20).map {"p(%2d) =%2d".format(it, pancake(it))} val lines = results.chunked(5).map { it.joinToString(" ") } lines.forEach { println(it) } }
477Pancake numbers
11kotlin
gfw4d
use strict; use warnings; use feature 'say'; sub pancake { my($n) = @_; my ($gap, $sum, $adj) = (2, 2, -1); while ($sum < $n) { $sum += $gap = $gap * 2 - 1 and $adj++ } $n + $adj; } my $out; $out .= sprintf "p(%2d) =%2d ", $_, pancake $_ for 1..20; say $out =~ s/.{1,55}\K /\n/gr; sub pancake2 { my ($n) = @_; my $numStacks = 1; my @goalStack = 1 .. $n; my %newStacks = my %stacks = (join(' ',@goalStack), 0); for my $k (1..1000) { my %nextStacks; for my $pos (2..$n) { for my $key (keys %newStacks) { my @arr = split ' ', $key; my $cakes = join ' ', (reverse @arr[0..$pos-1]), @arr[$pos..$ $nextStacks{$cakes} = $k unless $stacks{$cakes}; } } %stacks = (%stacks, (%newStacks = %nextStacks)); my $perms = scalar %stacks; my %inverted = reverse %stacks; return $k-1, $inverted{(sort keys %inverted)[-1]} if $perms == $numStacks; $numStacks = $perms; } } say "\nThe maximum number of flips to sort a given number of elements is:"; for my $n (1..9) { my ($a,$b) = pancake2($n); say "pancake($n) = $a example: $b"; }
477Pancake numbers
2perl
nhliw
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > nMax { return } if l*2 >= sum && b >= branches { return } if b == br+1 { c[br].Mul(&rooted[n], cnt) } else { tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1))) c[br].Mul(&c[br], tmp) c[br].Div(&c[br], tmp.SetInt64(int64(b-br))) } if l*2 < sum { unrooted[sum].Add(&unrooted[sum], &c[br]) } if b < branches { rooted[sum].Add(&rooted[sum], &c[br]) } for m := n - 1; m > 0; m-- { tree(b, m, l, sum, &c[br]) } } } func bicenter(s int) { if s&1 == 0 { tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1) unrooted[s].Add(&unrooted[s], tmp) } } func main() { rooted[0].SetInt64(1) rooted[1].SetInt64(1) unrooted[0].SetInt64(1) unrooted[1].SetInt64(1) for n := 1; n <= nMax; n++ { tree(0, n, n, 1, big.NewInt(1)) bicenter(n) fmt.Printf("%d:%d\n", n, &unrooted[n]) } }
478Paraffins
0go
7zxr2
class PostfixToInfix { static class Expression { final static String ops = "-+/*^" String op, ex int precedence = 3 Expression(String e) { ex = e } Expression(String e1, String e2, String o) { ex = String.format "%s%s%s", e1, o, e2 op = o precedence = (ops.indexOf(o) / 2) as int } @Override String toString() { return ex } } static String postfixToInfix(final String postfix) { Stack<Expression> expr = new Stack<>() for (String token in postfix.split("\\s+")) { char c = token.charAt(0) int idx = Expression.ops.indexOf(c as int) if (idx != -1 && token.length() == 1) { Expression r = expr.pop() Expression l = expr.pop() int opPrecedence = (idx / 2) as int if (l.precedence < opPrecedence || (l.precedence == opPrecedence && c == '^' as char)) l.ex = '(' + l.ex + ')' if (r.precedence < opPrecedence || (r.precedence == opPrecedence && c != '^' as char)) r.ex = '(' + r.ex + ')' expr << new Expression(l.ex, r.ex, token) } else { expr << new Expression(token) } printf "%s ->%s%n", token, expr } expr.peek().ex } static void main(String[] args) { (["3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"]).each { String e -> printf "Postfix:%s%n", e printf "Infix:%s%n", postfixToInfix(e) println() } } }
472Parsing/RPN to infix conversion
7groovy
gf846
var f1 = function (x) { return x * 2; }, f2 = function (x) { return x * x; }, fs = function (f, s) { return function (s) { return s.map(f); } }, fsf1 = fs(f1), fsf2 = fs(f2);
468Partial function application
10javascript
7ztrd
def combine( snl, snr ): cl = {} if isinstance(snl, int): cl['1'] = snl elif isinstance(snl, string): cl[snl] = 1 else: cl.update( snl) if isinstance(snr, int): n = cl.get('1', 0) cl['1'] = n + snr elif isinstance(snr, string): n = cl.get(snr, 0) cl[snr] = n + 1 else: for k,v in snr.items(): n = cl.get(k, 0) cl[k] = n+v return cl def constrain(nsum, vn ): nn = {} nn.update(vn) n = nn.get('1', 0) nn['1'] = n - nsum return nn def makeMatrix( constraints ): vmap = set() for c in constraints: vmap.update( c.keys()) vmap.remove('1') nvars = len(vmap) vmap = sorted(vmap) mtx = [] for c in constraints: row = [] for vv in vmap: row.append(float(c.get(vv, 0))) row.append(-float(c.get('1',0))) mtx.append(row) if len(constraints) == nvars: print 'System appears solvable' elif len(constraints) < nvars: print 'System is not solvable - needs more constraints.' return mtx, vmap def SolvePyramid( vl, cnstr ): vl.reverse() constraints = [cnstr] lvls = len(vl) for lvln in range(1,lvls): lvd = vl[lvln] for k in range(lvls - lvln): sn = lvd[k] ll = vl[lvln-1] vn = combine(ll[k], ll[k+1]) if sn is None: lvd[k] = vn else: constraints.append(constrain( sn, vn )) print 'Constraint Equations:' for cstr in constraints: fset = ('%d*%s'%(v,k) for k,v in cstr.items() ) print ' + '.join(fset), ' = 0' mtx,vmap = makeMatrix(constraints) MtxSolve(mtx) d = len(vmap) for j in range(d): print vmap[j],'=', mtx[j][d] def MtxSolve(mtx): mDim = len(mtx) for j in range(mDim): rw0= mtx[j] f = 1.0/rw0[j] for k in range(j, mDim+1): rw0[k] *= f for l in range(1+j,mDim): rwl = mtx[l] f = -rwl[j] for k in range(j, mDim+1): rwl[k] += f * rw0[k] for j1 in range(1,mDim): j = mDim - j1 rw0= mtx[j] for l in range(0, j): rwl = mtx[l] f = -rwl[j] rwl[j] += f * rw0[j] rwl[mDim] += f * rw0[mDim] return mtx p = [ [151], [None,None], [40,None,None], [None,None,None,None], ['X', 11, 'Y', 4, 'Z'] ] addlConstraint = { 'X':1, 'Y':-1, 'Z':1, '1':0 } SolvePyramid( p, addlConstraint)
466Pascal's triangle/Puzzle
3python
mxqyh
import time from collections import deque from operator import itemgetter from typing import Tuple Pancakes = Tuple[int, ...] def flip(pancakes: Pancakes, position: int) -> Pancakes: return tuple([*reversed(pancakes[:position]), *pancakes[position:]]) def pancake(n: int) -> Tuple[Pancakes, int]: init_stack = tuple(range(1, n + 1)) stack_flips = {init_stack: 0} queue = deque([init_stack]) while queue: stack = queue.popleft() flips = stack_flips[stack] + 1 for i in range(2, n + 1): flipped = flip(stack, i) if flipped not in stack_flips: stack_flips[flipped] = flips queue.append(flipped) return max(stack_flips.items(), key=itemgetter(1)) if __name__ == : start = time.time() for n in range(1, 10): pancakes, p = pancake(n) print(f) print(f)
477Pancake numbers
3python
dk2n1
typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } typedef struct palgen_tag { integer power; integer next; int digit; bool even; } palgen_t; void init_palgen(palgen_t* palgen, int digit) { palgen->power = 10; palgen->next = digit * palgen->power - 1; palgen->digit = digit; palgen->even = false; } integer next_palindrome(palgen_t* p) { ++p->next; if (p->next == p->power * (p->digit + 1)) { if (p->even) p->power *= 10; p->next = p->digit * p->power; p->even = !p->even; } return p->next * (p->even ? 10 * p->power : p->power) + reverse(p->even ? p->next : p->next/10); } bool gapful(integer n) { integer m = n; while (m >= 10) m /= 10; return n % (n % 10 + 10 * m) == 0; } void print(int len, integer array[][len]) { for (int digit = 1; digit < 10; ++digit) { printf(, digit); for (int i = 0; i < len; ++i) printf(, array[digit - 1][i]); printf(); } } int main() { const int n1 = 20, n2 = 15, n3 = 10; const int m1 = 100, m2 = 1000; integer pg1[9][n1]; integer pg2[9][n2]; integer pg3[9][n3]; for (int digit = 1; digit < 10; ++digit) { palgen_t pgen; init_palgen(&pgen, digit); for (int i = 0; i < m2; ) { integer n = next_palindrome(&pgen); if (!gapful(n)) continue; if (i < n1) pg1[digit - 1][i] = n; else if (i < m1 && i >= m1 - n2) pg2[digit - 1][i - (m1 - n2)] = n; else if (i >= m2 - n3) pg3[digit - 1][i - (m2 - n3)] = n; ++i; } } printf(, n1); print(n1, pg1); printf(, n2, m1); print(n2, pg2); printf(, n3, m2); print(n3, pg3); return 0; }
480Palindromic gapful numbers
5c
xudwu
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) fmt.Println("postfix:", parseInfix(input)) } func parseInfix(e string) (rpn string) { var stack []string
471Parsing/Shunting-yard algorithm
0go
xucwf
a `nmul` n = map (*n) a a `ndiv` n = map (`div` n) a instance (Integral a) => Num [a] where (+) = zipWith (+) negate = map negate a * b = foldr f undefined b where f x z = (a `nmul` x) + (0: z) abs _ = undefined signum _ = undefined fromInteger n = fromInteger n: repeat 0 repl a n = concatMap (: replicate (n-1) 0) a cycleIndexS2 a b = (a*a + b)`ndiv` 2 cycleIndexS4 a b c d = ((a ^ 4) + (a ^ 2 * b) `nmul` 6 + (a * c) `nmul` 8 + (b ^ 2) `nmul` 3 + d `nmul` 6) `ndiv` 24 a598 = x1 x1 = 1: ((x1^3) + ((x2*x1)`nmul` 3) + (x3`nmul`2)) `ndiv` 6 x2 = x1`repl`2 x3 = x1`repl`3 x4 = x1`repl`4 a678 = 0: cycleIndexS4 x1 x2 x3 x4 a599 = cycleIndexS2 (0: tail x1) (0: tail x2) a602 = a678 - a599 + x2 main = mapM_ print $ take 200 $ zip [0 ..] a602
478Paraffins
8haskell
8ry0z
import Debug.Trace data Expression = Const String | Exp Expression String Expression infixFromRPN :: String -> Expression infixFromRPN = head . foldl buildExp [] . words buildExp :: [Expression] -> String -> [Expression] buildExp stack x | (not . isOp) x = let v = Const x: stack in trace (show v) v | otherwise = let v = Exp l x r: rest in trace (show v) v where r: l: rest = stack isOp = (`elem` ["^", "*", "/", "+", "-"]) main :: IO () main = mapM_ ( \s -> putStr (s <> "\n >> (print . infixFromRPN) s >> putStrLn [] ) [ "3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^", "1 4 + 5 3 + 2 3 * * *", "1 2 * 3 4 * *", "1 2 + 3 4 + +" ] instance Show Expression where show (Const x) = x show exp@(Exp l op r) = left <> " " <> op <> " " <> right where left | leftNeedParen = "( " <> show l <> " )" | otherwise = show l right | rightNeedParen = "( " <> show r <> " )" | otherwise = show r leftNeedParen = (leftPrec < opPrec) || ((leftPrec == opPrec) && rightAssoc exp) rightNeedParen = (rightPrec < opPrec) || ((rightPrec == opPrec) && leftAssoc exp) leftPrec = precedence l rightPrec = precedence r opPrec = precedence exp leftAssoc :: Expression -> Bool leftAssoc (Const _) = False leftAssoc (Exp _ op _) = op `notElem` ["^", "*", "+"] rightAssoc :: Expression -> Bool rightAssoc (Const _) = False rightAssoc (Exp _ op _) = op == "^" precedence :: Expression -> Int precedence (Const _) = 5 precedence (Exp _ op _) | op == "^" = 4 | op `elem` ["*", "/"] = 3 | op `elem` ["+", "-"] = 2 | otherwise = 0
472Parsing/RPN to infix conversion
8haskell
nh4ie
require def prime_partition(x, n) Prime.each(x).to_a.combination(n).detect{|primes| primes.sum == x} end TESTCASES = [[99809, 1], [18, 2], [19, 3], [20, 4], [2017, 24], [22699, 1], [22699, 2], [22699, 3], [22699, 4], [40355, 3]] TESTCASES.each do |prime, num| res = prime_partition(prime, num) str = res.nil?? : res.join() puts end
467Partition an integer x into n primes
14ruby
7zzri
package main import ( "fmt" "math/big" )
473Parallel calculations
0go
p9tbg
(ns rosettacode.parsing-rpn-calculator-algorithm (:require clojure.math.numeric-tower clojure.string clojure.pprint)) (def operators "the only allowable operators for our calculator" {"+" + "-" - "*" * "/" / "^" clojure.math.numeric-tower/expt}) (defn rpn "takes a string and returns a lazy-seq of all the stacks" [string] (letfn [(rpn-reducer [stack item] (if (contains? operators item) (let [operand-1 (peek stack) stack-1 (pop stack)] (conj (pop stack-1) ((operators item) (peek stack-1) operand-1))) (conj stack (Long. item))))] (reductions rpn-reducer [] (clojure.string/split string #"\s+")))) (let [stacks (rpn "3 4 2 * 1 5 - 2 3 ^ ^ / +")] (println "stacks: ") (clojure.pprint/pprint stacks) (print "answer:" (->> stacks last first)))
479Parsing/RPN calculator algorithm
6clojure
0g3sj
import Text.Printf prec :: String -> Int prec "^" = 4 prec "*" = 3 prec "/" = 3 prec "+" = 2 prec "-" = 2 leftAssoc :: String -> Bool leftAssoc "^" = False leftAssoc _ = True isOp :: String -> Bool isOp [t] = t `elem` "-+/*^" isOp _ = False simSYA :: [String] -> [([String], [String], String)] simSYA xs = final <> [lastStep] where final = scanl f ([], [], "") xs lastStep = ( \(x, y, _) -> (reverse y <> x, [], "") ) $ last final f (out, st, _) t | isOp t = ( reverse (takeWhile testOp st) <> out, (t:) (dropWhile testOp st), t ) | t == "(" = (out, "(": st, t) | t == ")" = ( reverse (takeWhile (/= "(") st) <> out, tail $ dropWhile (/= "(") st, t ) | otherwise = (t: out, st, t) where testOp x = isOp x && ( leftAssoc t && prec t == prec x || prec t < prec x ) main :: IO () main = do a <- getLine printf "%30s%20s%7s" "Output" "Stack" "Token" mapM_ ( \(x, y, z) -> printf "%30s%20s%7s\n" (unwords $ reverse x) (unwords y) z ) $ simSYA $ words a
471Parsing/Shunting-yard algorithm
8haskell
ywp66
struct TreeNode<T> { value: T, left: Option<Box<TreeNode<T>>>, right: Option<Box<TreeNode<T>>>, } impl <T> TreeNode<T> { fn my_map<U,F>(&self, f: &F) -> TreeNode<U> where F: Fn(&T) -> U { TreeNode { value: f(&self.value), left: match self.left { None => None, Some(ref n) => Some(Box::new(n.my_map(f))), }, right: match self.right { None => None, Some(ref n) => Some(Box::new(n.my_map(f))), }, } } } fn main() { let root = TreeNode { value: 3, left: Some(Box::new(TreeNode { value: 55, left: None, right: None, })), right: Some(Box::new(TreeNode { value: 234, left: Some(Box::new(TreeNode { value: 0, left: None, right: None, })), right: None, })), }; root.my_map(&|x| { println!("{}" , x)}); println!("---------------"); let new_root = root.my_map(&|x| *x as f64 * 333.333f64); new_root.my_map(&|x| { println!("{}" , x) }); }
470Parametric polymorphism
15rust
rtng5
case class Tree[+A](value: A, left: Option[Tree[A]], right: Option[Tree[A]]) { def map[B](f: A => B): Tree[B] = Tree(f(value), left map (_.map(f)), right map (_.map(f))) }
470Parametric polymorphism
16scala
h6tja
null
468Partial function application
11kotlin
9qxmh
null
467Partition an integer x into n primes
15rust
j3372
object PartitionInteger { def sieve(nums: LazyList[Int]): LazyList[Int] = LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))
467Partition an integer x into n primes
16scala
bmmk6
import Control.Parallel.Strategies (parMap, rdeepseq) import Control.DeepSeq (NFData) import Data.List (maximumBy) import Data.Function (on) nums :: [Integer] nums = [ 112272537195293 , 112582718962171 , 112272537095293 , 115280098190773 , 115797840077099 , 1099726829285419 ] lowestFactor :: Integral a => a -> a -> a lowestFactor s n | even n = 2 | otherwise = head y where y = [ x | x <- [s .. ceiling . sqrt $ fromIntegral n] ++ [n] , n `rem` x == 0 , odd x ] primeFactors :: Integral a => a -> a -> [a] primeFactors l n = f n l [] where f n l xs = if n > 1 then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l: xs) else xs minPrimes :: (Control.DeepSeq.NFData a, Integral a) => [a] -> (a, [a]) minPrimes ns = (\(x, y) -> (x, primeFactors y x)) $ maximumBy (compare `on` snd) $ zip ns (parMap rdeepseq (lowestFactor 3) ns) main :: IO () main = print $ minPrimes nums
473Parallel calculations
8haskell
fbgd1
def pancake(n) gap = 2 sum = 2 adj = -1 while sum < n adj = adj + 1 gap = gap * 2 - 1 sum = sum + gap end return n + adj end for i in 0 .. 3 for j in 1 .. 5 n = i * 5 + j print % [n, pancake(n)] end print end
477Pancake numbers
14ruby
tpuf2
import java.math.BigInteger; import java.util.Arrays; class Test { final static int nMax = 250; final static int nBranches = 4; static BigInteger[] rooted = new BigInteger[nMax + 1]; static BigInteger[] unrooted = new BigInteger[nMax + 1]; static BigInteger[] c = new BigInteger[nBranches]; static void tree(int br, int n, int l, int inSum, BigInteger cnt) { int sum = inSum; for (int b = br + 1; b <= nBranches; b++) { sum += n; if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return; BigInteger tmp = rooted[n]; if (b == br + 1) { c[br] = tmp.multiply(cnt); } else { c[br] = c[br].multiply(tmp.add(BigInteger.valueOf(b - br - 1))); c[br] = c[br].divide(BigInteger.valueOf(b - br)); } if (l * 2 < sum) unrooted[sum] = unrooted[sum].add(c[br]); if (b < nBranches) rooted[sum] = rooted[sum].add(c[br]); for (int m = n - 1; m > 0; m--) tree(b, m, l, sum, c[br]); } } static void bicenter(int s) { if ((s & 1) == 0) { BigInteger tmp = rooted[s / 2]; tmp = tmp.add(BigInteger.ONE).multiply(rooted[s / 2]); unrooted[s] = unrooted[s].add(tmp.shiftRight(1)); } } public static void main(String[] args) { Arrays.fill(rooted, BigInteger.ZERO); Arrays.fill(unrooted, BigInteger.ZERO); rooted[0] = rooted[1] = BigInteger.ONE; unrooted[0] = unrooted[1] = BigInteger.ONE; for (int n = 1; n <= nMax; n++) { tree(0, n, n, 1, BigInteger.ONE); bicenter(n); System.out.printf("%d:%s%n", n, unrooted[n]); } } }
478Paraffins
9java
e2da5
use DBI; my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password'); $statment = $db->prepare("UPDATE players SET name =?, score =?, active =? WHERE jerseyNum =?"); $rows_affected = $statment->execute("Smith, Steve",42,'true',99);
475Parameterized SQL statement
2perl
bmnk4
void pascaltriangle(unsigned int n) { unsigned int c, i, j, k; for(i=0; i < n; i++) { c = 1; for(j=1; j <= 2*(n-1-i); j++) printf(); for(k=0; k <= i; k++) { printf(, c); c = c * (i-k)/(k+1); } printf(); } } int main() { pascaltriangle(8); return 0; }
481Pascal's triangle
5c
ywu6f
class Tree<T> { var value: T? var left: Tree<T>? var right: Tree<T>? func replaceAll(value: T?) { self.value = value left?.replaceAll(value) right?.replaceAll(value) } }
470Parametric polymorphism
17swift
4do5g
require 'rref' pyramid = [ [ 151], [nil,nil], [40,nil,nil], [nil,nil,nil,nil], [, 11,, 4,] ] pyramid.each{|row| p row} equations = [[1,-1,1,0]] def parse_equation(str) eqn = [0] * 4 lhs, rhs = str.split() eqn[3] = rhs.to_i for term in lhs.split() case term when then eqn[0] += 1 when then eqn[1] += 1 when then eqn[2] += 1 else eqn[3] -= term.to_i end end eqn end -2.downto(-5) do |row| pyramid[row].each_index do |col| val = pyramid[row][col] sum = % [pyramid[row+1][col], pyramid[row+1][col+1]] if val.nil? pyramid[row][col] = sum else equations << parse_equation(sum + ) end end end reduced = convert_to(reduced_row_echelon_form(equations), :to_i) for eqn in reduced if eqn[0] + eqn[1] + eqn[2]!= 1 fail elsif eqn[0] == 1 then x = eqn[3] elsif eqn[1] == 1 then y = eqn[3] elsif eqn[2] == 1 then z = eqn[3] end end puts puts puts puts answer = [] for row in pyramid answer << row.collect {|cell| eval cell.to_s} end puts answer.each{|row| p row}
466Pascal's triangle/Puzzle
14ruby
cs09k
package main import ( "crypto/sha256" "encoding/hex" "log" "sync" ) var hh = []string{ "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad", "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b", "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f", } func main() { log.SetFlags(0) hd := make([][sha256.Size]byte, len(hh)) for i, h := range hh { hex.Decode(hd[i][:], []byte(h)) } var wg sync.WaitGroup wg.Add(26) for c := byte('a'); c <= 'z'; c++ { go bf4(c, hd, &wg) } wg.Wait() } func bf4(c byte, hd [][sha256.Size]byte, wg *sync.WaitGroup) { p := []byte("aaaaa") p[0] = c p1 := p[1:] p: for { ph := sha256.Sum256(p) for i, h := range hd { if h == ph { log.Println(string(p), hh[i]) } } for i, v := range p1 { if v < 'z' { p1[i]++ continue p } p1[i] = 'a' } wg.Done() return } }
476Parallel brute force
0go
j307d
$updatePlayers = . ; $dbh = new PDO( , , ); $updateStatement = $dbh->prepare( $updatePlayers ); $updateStatement->bindValue( 1, , PDO::PARAM_STR ); $updateStatement->bindValue( 2, 42, PDO::PARAM_INT ); $updateStatement->bindValue( 3, 1, PDO::PARAM_INT ); $updateStatement->bindValue( 4, 99, PDO::PARAM_INT ); $updateStatement->execute(); $updateStatement = $dbh->prepare( $updatePlayers ); $updateStatement->execute( array( , 42, 1, 99 ) );
475Parameterized SQL statement
12php
6e73g
from ipaddress import ip_address from urllib.parse import urlparse tests = [ , , , , , , ] def parse_ip_port(netloc): try: ip = ip_address(netloc) port = None except ValueError: parsed = urlparse(' ip = ip_address(parsed.hostname) port = parsed.port return ip, port for address in tests: ip, port = parse_ip_port(address) hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip)) print(.format( str(ip), hex_ip, ip.version, port ))
469Parse an IP Address
3python
8r40o
import java.util.Stack; public class PostfixToInfix { public static void main(String[] args) { for (String e : new String[]{"3 4 2 * 1 5 - 2 3 ^ ^ / +", "1 2 + 3 4 + ^ 5 6 + ^"}) { System.out.printf("Postfix:%s%n", e); System.out.printf("Infix:%s%n", postfixToInfix(e)); System.out.println(); } } static String postfixToInfix(final String postfix) { class Expression { final static String ops = "-+/*^"; String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format("%s%s%s", e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } @Override public String toString() { return ex; } } Stack<Expression> expr = new Stack<>(); for (String token : postfix.split("\\s+")) { char c = token.charAt(0); int idx = Expression.ops.indexOf(c); if (idx != -1 && token.length() == 1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec || (l.prec == opPrec && c == '^')) l.ex = '(' + l.ex + ')'; if (r.prec < opPrec || (r.prec == opPrec && c != '^')) r.ex = '(' + r.ex + ')'; expr.push(new Expression(l.ex, r.ex, token)); } else { expr.push(new Expression(token)); } System.out.printf("%s ->%s%n", token, expr); } return expr.peek().ex; } }
472Parsing/RPN to infix conversion
9java
q5cxa
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) } } func findPrimePartition(sieve: PrimeSieve, number: Int, count: Int, minPrime: Int, primes: inout [Int], index: Int) -> Bool { if count == 1 { if number >= minPrime && sieve.isPrime(number: number) { primes[index] = number return true } return false } if minPrime >= number { return false } for p in minPrime..<number { if sieve.isPrime(number: p) && findPrimePartition(sieve: sieve, number: number - p, count: count - 1, minPrime: p + 1, primes: &primes, index: index + 1) { primes[index] = p return true } } return false } func printPrimePartition(sieve: PrimeSieve, number: Int, count: Int) { var primes = Array(repeating: 0, count: count) if!findPrimePartition(sieve: sieve, number: number, count: count, minPrime: 2, primes: &primes, index: 0) { print("\(number) cannot be partitioned into \(count) primes.") } else { print("\(number) = \(primes[0])", terminator: "") for i in 1..<count { print(" + \(primes[i])", terminator: "") } print() } } let sieve = PrimeSieve(size: 100000) printPrimePartition(sieve: sieve, number: 99809, count: 1) printPrimePartition(sieve: sieve, number: 18, count: 2) printPrimePartition(sieve: sieve, number: 19, count: 3) printPrimePartition(sieve: sieve, number: 20, count: 4) printPrimePartition(sieve: sieve, number: 2017, count: 24) printPrimePartition(sieve: sieve, number: 22699, count: 1) printPrimePartition(sieve: sieve, number: 22699, count: 2) printPrimePartition(sieve: sieve, number: 22699, count: 3) printPrimePartition(sieve: sieve, number: 22699, count: 4) printPrimePartition(sieve: sieve, number: 40355, count: 3)
467Partition an integer x into n primes
17swift
rttgg
object PascalTriangle extends App { val (x, y, z) = pascal(11, 4, 40, 151) def pascal(a: Int, b: Int, mid: Int, top: Int): (Int, Int, Int) = { val y = (top - 4 * (a + b)) / 7 val x = mid - 2 * a - y (x, y, y - x) } println(if (x != 0) s"Solution is: x = $x, y = $y, z = $z" else "There is no solution.") }
466Pascal's triangle/Puzzle
16scala
uinv8
use strict; use warnings; use feature 'say'; use English; use Const::Fast; use Getopt::Long; use Math::Random; const my @lcs => 'a' .. 'z'; const my @ucs => 'A' .. 'Z'; const my @digits => 0 .. 9; const my $others => q{!" my $pwd_length = 8; my $num_pwds = 6; my $seed_phrase = 'TOO MANY SECRETS'; my %opts = ( 'password_length=i' => \$pwd_length, 'num_passwords=i' => \$num_pwds, 'seed_phrase=s' => \$seed_phrase, 'help!' => sub {command_line_help(); exit 0} ); command_line_help() and exit 1 unless $num_pwds >= 1 and $pwd_length >= 4 and GetOptions(%opts); random_set_seed_from_phrase($seed_phrase); say gen_password() for 1 .. $num_pwds; sub gen_password { my @generators = (\&random_lc, \&random_uc, \&random_digit, \&random_other); my @chars = map {$ARG->()} @generators; push @chars, $generators[random_uniform_integer(1, 0, 3)]->() for 1 .. $pwd_length - 4; join '', random_permutation(@chars); } sub random_lc { $lcs[ random_uniform_integer(1, 0, $ sub random_uc { $ucs[ random_uniform_integer(1, 0, $ sub random_digit { $digits[ random_uniform_integer(1, 0, $ sub random_other { substr($others, random_uniform_integer(1, 0, length($others)-1), 1) } sub command_line_help { say <<~END Usage: $PROGRAM_NAME [--password_length=<l> default: 8, minimum: 4] [--num_passwords=<n> default: 6, minimum: 1] [--seed_phrase=<s> default: TOO MANY SECRETS (optional)] [--help] END }
463Password generator
2perl
ijpo3
import Control.Concurrent (setNumCapabilities) import Crypto.Hash (hashWith, SHA256 (..), Digest) import Control.Monad (replicateM, join, (>=>)) import Control.Monad.Par (runPar, get, spawnP) import Data.ByteString (pack) import Data.List.Split (chunksOf) import GHC.Conc (getNumProcessors) import Text.Printf (printf) hashedValues :: [Digest SHA256] hashedValues = read <$> [ "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b" , "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f" , "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad" ] bruteForce :: Int -> [(String, String)] bruteForce n = runPar $ join <$> (mapM (spawnP . foldr findMatch []) >=> mapM get) chunks where chunks = chunksOf (26^5 `div` n) $ replicateM 5 [97..122] findMatch s accum | hashed `elem` hashedValues = (show hashed, show bStr): accum | otherwise = accum where bStr = pack s hashed = hashWith SHA256 bStr main :: IO () main = do cpus <- getNumProcessors setNumCapabilities cpus printf "Using%d cores\n" cpus mapM_ (uncurry (printf "%s ->%s\n")) (bruteForce cpus)
476Parallel brute force
8haskell
o7c8p
import static java.lang.System.out; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; public interface ParallelCalculations { public static final long[] NUMBERS = { 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 }; public static void main(String... arguments) { stream(NUMBERS) .unordered() .parallel() .mapToObj(ParallelCalculations::minimalPrimeFactor) .max(comparing(a -> a[0])) .ifPresent(res -> out.printf( "%d has the largest minimum prime factor:%d%n", res[1], res[0] )); } public static long[] minimalPrimeFactor(long n) { for (long i = 2; n >= i * i; i++) { if (n % i == 0) { return new long[]{i, n}; } } return new long[]{n, n}; } }
473Parallel calculations
9java
0glse
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix:%s%n", infixToPostfix(infix)); } static String infixToPostfix(String infix) { final String ops = "-+/*^"; StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); for (String token : infix.split("\\s")) { if (token.isEmpty()) continue; char c = token.charAt(0); int idx = ops.indexOf(c);
471Parsing/Shunting-yard algorithm
9java
dkrn9
null
478Paraffins
11kotlin
ky0h3
const Associativity = { left: 0, right: 1, both: 2, }; const operators = { '+': { precedence: 2, associativity: Associativity.both }, '-': { precedence: 2, associativity: Associativity.left }, '*': { precedence: 3, associativity: Associativity.both }, '/': { precedence: 3, associativity: Associativity.left }, '^': { precedence: 4, associativity: Associativity.right }, }; class NumberNode { constructor(text) { this.text = text; } toString() { return this.text; } } class InfixNode { constructor(fnname, operands) { this.fnname = fnname; this.operands = operands; } toString(parentPrecedence = 0) { const op = operators[this.fnname]; const leftAdd = op.associativity === Associativity.right ? 0.01 : 0; const rightAdd = op.associativity === Associativity.left ? 0.01 : 0; if (this.operands.length !== 2) throw Error("invalid operand count"); const result = this.operands[0].toString(op.precedence + leftAdd) +` ${this.fnname} ${this.operands[1].toString(op.precedence + rightAdd)}`; if (parentPrecedence > op.precedence) return `( ${result} )`; else return result; } } function rpnToTree(tokens) { const stack = []; console.log(`input = ${tokens}`); for (const token of tokens.split(" ")) { if (token in operators) { const op = operators[token], arity = 2;
472Parsing/RPN to infix conversion
10javascript
ij5ol
function map(f, ...) local t = {} for k, v in ipairs(...) do t[#t+1] = f(v) end return t end function timestwo(n) return n * 2 end function squared(n) return n ^ 2 end function partial(f, arg) return function(...) return f(arg, ...) end end timestwo_s = partial(map, timestwo) squared_s = partial(map, squared) print(table.concat(timestwo_s{0, 1, 2, 3}, ', ')) print(table.concat(squared_s{0, 1, 2, 3}, ', ')) print(table.concat(timestwo_s{2, 4, 6, 8}, ', ')) print(table.concat(squared_s{2, 4, 6, 8}, ', '))
468Partial function application
1lua
csq92
import javax.xml.bind.DatatypeConverter; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ParallelBruteForce { public static void main(String[] args) throws NoSuchAlgorithmException {
476Parallel brute force
9java
wvzej
var onmessage = function(event) { postMessage({"n" : event.data.n, "factors" : factor(event.data.n), "id" : event.data.id}); }; function factor(n) { var factors = []; for(p = 2; p <= n; p++) { if((n % p) == 0) { factors[factors.length] = p; n /= p; } } return factors; }
473Parallel calculations
10javascript
dk4nu
function Stack() { this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.length = length; } function push(element) { this.dataStore[this.top++] = element; } function pop() { return this.dataStore[--this.top]; } function peek() { return this.dataStore[this.top-1]; } function length() { return this.top; } var infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; infix = infix.replace(/\s+/g, '');
471Parsing/Shunting-yard algorithm
10javascript
6eb38
import sqlite3 db = sqlite3.connect(':memory:') db.execute('create temp table players (name, score, active, jerseyNum)') db.execute('insert into players values (,0,,99)') db.execute('insert into players values (,0,,100)') db.execute('update players set name=?, score=?, active=? where jerseyNum=?', ('Smith, Steve', 42, True, 99)) db.execute('update players set name=:name, score=:score, active=:active where jerseyNum=:num', {'num': 100, 'name': 'John Doe', 'active': False, 'score': -1} ) for row in db.execute('select * from players'): print(row)
475Parameterized SQL statement
3python
p9dbm
(defn pascal [n] (let [newrow (fn newrow [lst ret] (if lst (recur (rest lst) (conj ret (+ (first lst) (or (second lst) 0)))) ret)) genrow (fn genrow [n lst] (when (< 0 n) (do (println lst) (recur (dec n) (conj (newrow lst []) 1)))))] (genrow n [1]))) (pascal 4)
481Pascal's triangle
6clojure
287l1
null
472Parsing/RPN to infix conversion
11kotlin
1c3pd
null
476Parallel brute force
11kotlin
bmikb
null
473Parallel calculations
11kotlin
e26a4
package main import ( "fmt" "strings" ) func binomial(n, k int) int { if n < k { return 0 } if n == 0 || k == 0 { return 1 } num := 1 for i := k + 1; i <= n; i++ { num *= i } den := 1 for i := 2; i <= n-k; i++ { den *= i } return num / den } func pascalUpperTriangular(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(j, i) } } return m } func pascalLowerTriangular(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(i, j) } } return m } func pascalSymmetric(n int) [][]int { m := make([][]int, n) for i := 0; i < n; i++ { m[i] = make([]int, n) for j := 0; j < n; j++ { m[i][j] = binomial(i+j, i) } } return m } func printMatrix(title string, m [][]int) { n := len(m) fmt.Println(title) fmt.Print("[") for i := 0; i < n; i++ { if i > 0 { fmt.Print(" ") } mi := strings.Replace(fmt.Sprint(m[i]), " ", ", ", -1) fmt.Print(mi) if i < n-1 { fmt.Println(",") } else { fmt.Println("]\n") } } } func main() { printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5)) printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5)) printMatrix("Pascal symmetric matrix", pascalSymmetric(5)) }
474Pascal matrix generation
0go
xuywf
require 'sqlite3' db = SQLite3::Database.new() db.execute('create temp table players (name, score, active, jerseyNum)') db.execute('insert into players values (,0,,99)') db.execute('insert into players values (,0,,100)') db.execute('insert into players values (,0,,101)') db.execute('update players set name=?, score=?, active=? where jerseyNum=?', 'Smith, Steve', 42, true, 99) db.execute('update players set name=:name, score=:score, active=:active where jerseyNum=:num', :num => 100, :name => 'John Doe', :active => false, :score => -1 ) stmt = db.prepare('update players set name=?4, score=?3, active=?2 where jerseyNum=?1') stmt.bind_param(1, 101) stmt.bind_param(2, true) stmt.bind_param(3, 3) stmt.bind_param(4, ) stmt.execute db.execute2('select * from players') {|row| p row}
475Parameterized SQL statement
14ruby
alt1s
function tokenize(rpn) local out = {} local cnt = 0 for word in rpn:gmatch("%S+") do table.insert(out, word) cnt = cnt + 1 end return {tokens = out, pos = 1, size = cnt} end function advance(lex) if lex.pos <= lex.size then lex.pos = lex.pos + 1 return true else return false end end function current(lex) return lex.tokens[lex.pos] end function isOperator(sym) return sym == '+' or sym == '-' or sym == '*' or sym == '/' or sym == '^' end function buildTree(lex) local stack = {} while lex.pos <= lex.size do local sym = current(lex) advance(lex) if isOperator(sym) then local b = table.remove(stack) local a = table.remove(stack) local t = {op=sym, left=a, right=b} table.insert(stack, t) else table.insert(stack, sym) end end return table.remove(stack) end function infix(tree) if type(tree) == "table" then local a = {} local b = {} if type(tree.left) == "table" then a = '(' .. infix(tree.left) .. ')' else a = tree.left end if type(tree.right) == "table" then b = '(' .. infix(tree.right) .. ')' else b = tree.right end return a .. ' ' .. tree.op .. ' ' .. b else return tree end end function convert(str) local lex = tokenize(str) local tree = buildTree(lex) print(infix(tree)) end function main() convert("3 4 2 * 1 5 - 2 3 ^ ^ / +") convert("1 2 + 3 4 + ^ 5 6 + ^") end main()
472Parsing/RPN to infix conversion
1lua
al61v
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) 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 ord(n uint) string { var suffix string if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) { suffix = "th" } else { switch n % 10 { case 1: suffix = "st" case 2: suffix = "nd" case 3: suffix = "rd" default: suffix = "th" } } return fmt.Sprintf("%s%s", commatize(n), suffix) } func main() { const max = 10_000_000 data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14}, {1e6, 1e6, 16}, {1e7, 1e7, 18}} results := make(map[uint][]uint64) for _, d := range data { for i := d[0]; i <= d[1]; i++ { results[i] = make([]uint64, 9) } } var p uint64 outer: for d := uint64(1); d < 10; d++ { count := uint(0) pow := uint64(1) fl := d * 11 for nd := 3; nd < 20; nd++ { slim := (d + 1) * pow for s := d * pow; s < slim; s++ { e := reverse(s) mlim := uint64(1) if nd%2 == 1 { mlim = 10 } for m := uint64(0); m < mlim; m++ { if nd%2 == 0 { p = s*pow*10 + e } else { p = s*pow*100 + m*pow*10 + e } if p%fl == 0 { count++ if _, ok := results[count]; ok { results[count][d-1] = p } if count == max { continue outer } } } } if nd%2 == 1 { pow *= 10 } } } for _, d := range data { if d[0] != d[1] { fmt.Printf("%s to%s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1])) } else { fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0])) } for i := 1; i <= 9; i++ { fmt.Printf("%d: ", i) for j := d[0]; j <= d[1]; j++ { fmt.Printf("%*d ", d[2], results[j][i-1]) } fmt.Println() } fmt.Println() } }
480Palindromic gapful numbers
0go
l07cw
null
471Parsing/Shunting-yard algorithm
11kotlin
0gvsf
import Data.List (transpose) import System.Environment (getArgs) import Text.Printf (printf) pascal :: [[Int]] pascal = iterate (\row -> 1: zipWith (+) row (tail row) ++ [1]) [1] pascLow :: Int -> [[Int]] pascLow n = zipWith (\row i -> row ++ replicate (n-i) 0) (take n pascal) [1..] pascUp :: Int -> [[Int]] pascUp = transpose . pascLow pascSym :: Int -> [[Int]] pascSym n = take n . map (take n) . transpose $ pascal printMat :: String -> [[Int]] -> IO () printMat title mat = do putStrLn $ title ++ "\n" mapM_ (putStrLn . concatMap (printf "%2d")) mat putStrLn "\n" main :: IO () main = do ns <- fmap (map read) getArgs case ns of [n] -> do printMat "Lower triangular" $ pascLow n printMat "Upper triangular" $ pascUp n printMat "Symmetric" $ pascSym n _ -> error "Usage: pascmat <number>"
474Pascal matrix generation
8haskell
ywh66
import slick.jdbc.H2Profile.api._ import slick.sql.SqlProfile.ColumnOption.SqlType import scala.concurrent.Await import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration.Duration object PlayersApp extends App { lazy val playerRecords = TableQuery[PlayerRecords] val db = Database.forURL("jdbc:h2:mem:test1;DB_CLOSE_DELAY=-1", driver = "org.h2.Driver")
475Parameterized SQL statement
16scala
q5yxw
require 'ipaddr' TESTCASES = [, , , , , ] output = [%w(String Address Port Family Hex), %w(------ ------- ---- ------ ---)] def output_table(rows) widths = [] rows.each {|row| row.each_with_index {|col, i| widths[i] = [widths[i].to_i, col.to_s.length].max }} format = widths.map {|size| }.join() rows.each {|row| puts format % row} end TESTCASES.each do |str| case str when /\A\[(?<address> .* )\]:(?<port> \d+ )\z/x address, port = $~[:address], $~[:port] when /\A(?<address> [^:]+ ):(?<port> \d+ )\z/x address, port = $~[:address], $~[:port] else address, port = str, nil end ip_addr = IPAddr.new(address) family = if ip_addr.ipv4? family = if ip_addr.ipv6? output << [str, ip_addr.to_s, port.to_s, family, ip_addr.to_i.to_s(16)] end output_table(output)
469Parse an IP Address
14ruby
ijroh
use Digest::SHA qw/sha256_hex/; use threads; use threads::shared; my @results :shared; print "$_: ",join(" ",search($_)), "\n" for (qw/ 1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b 74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f /); sub search { my $hash = shift; @results = (); $_->join() for map { threads->create('tsearch', $_, $hash) } 0..25; return @results; } sub tsearch { my($tnum, $hash) = @_; my $s = chr(ord("a")+$tnum) . "aaaa"; for (1..456976) { push @results, $s if sha256_hex($s) eq $hash; $s++; } }
476Parallel brute force
2perl
6er36
import Control.Monad (guard) palindromic :: Int -> Bool palindromic n = d == reverse d where d = show n gapful :: Int -> Bool gapful n = n `rem` firstLastDigit == 0 where firstLastDigit = read [head asDigits, last asDigits] asDigits = show n result :: Int -> [Int] result d = do x <- [(d+100),(d+110)..] guard $ palindromic x && gapful x pure x showSets :: (Int -> String) -> IO () showSets r = go 1 where go n = if n <= 9 then do putStrLn (show n ++ ": " ++ r n) go (succ n) else pure () main :: IO () main = do putStrLn "\nFirst 20 palindromic gapful numbers ending in:" showSets (show . take 20 . result) putStrLn "\nLast 15 of first 100 palindromic gapful numbers ending in:" showSets (show . drop 85 . take 100 . result) putStrLn "\nLast 10 of first 1000 palindromic gapful numbers ending in:" showSets (show . drop 990 . take 1000 . result) putStrLn "\ndone."
480Palindromic gapful numbers
8haskell
1c8ps
use Math::GMPz; my $nmax = 250; my $nbranches = 4; my @rooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @unrooted = map { Math::GMPz->new($_) } 1,1,(0) x $nmax; my @c = map { Math::GMPz->new(0) } 0 .. $nbranches-1; sub tree { my($br, $n, $l, $sum, $cnt) = @_; for my $b ($br+1 .. $nbranches) { $sum += $n; return if $sum > $nmax || ($l*2 >= $sum && $b >= $nbranches); if ($b == $br+1) { $c[$br] = $rooted[$n] * $cnt; } else { $c[$br] *= $rooted[$n] + $b - $br - 1; $c[$br] /= $b - $br; } $unrooted[$sum] += $c[$br] if $l*2 < $sum; return if $b >= $nbranches; $rooted[$sum] += $c[$br]; for my $m (reverse 1 .. $n-1) { next if $sum+$m > $nmax; tree($b, $m, $l, $sum, $c[$br]); } } } sub bicenter { my $s = shift; $unrooted[$s] += $rooted[$s/2] * ($rooted[$s/2]+1) / 2 unless $s & 1; } for my $n (1 .. $nmax) { tree(0, $n, $n, 1, Math::GMPz->new(1)); bicenter($n); print "$n: $unrooted[$n]\n"; }
478Paraffins
2perl
3a5zs
int is_pangram(const char *s) { const char *alpha = ; char ch, wasused[26] = {0}; int total = 0; while ((ch = *s++) != '\0') { const char *p; int idx; if ((p = strchr(alpha, ch)) == NULL) continue; idx = (p - alpha) % 26; total += !wasused[idx]; wasused[idx] = 1; if (total == 26) return 1; } return 0; } int main(void) { int i; const char *tests[] = { , }; for (i = 0; i < 2; i++) printf(%s\, tests[i], is_pangram(tests[i])?:); return 0; }
482Pangram checker
5c
vo72o
-- This works in Oracle's SQL*Plus command line utility VARIABLE P_NAME VARCHAR2(20); VARIABLE P_SCORE NUMBER; VARIABLE P_ACTIVE VARCHAR2(5); VARIABLE P_JERSEYNUM NUMBER; BEGIN :P_NAME:= 'Smith, Steve'; :P_SCORE:= 42; :P_ACTIVE:= 'TRUE'; :P_JERSEYNUM:= 99; END; / DROP TABLE players; CREATE TABLE players ( NAME VARCHAR2(20), SCORE NUMBER, ACTIVE VARCHAR2(5), JERSEYNUM NUMBER ); INSERT INTO players VALUES ('No name',0,'FALSE',99); commit; SELECT * FROM players; UPDATE players SET name =:P_NAME, score =:P_SCORE, active =:P_ACTIVE WHERE jerseyNum =:P_JERSEYNUM; commit; SELECT * FROM players;
475Parameterized SQL statement
19sql
8rc02
use std::{ net::{IpAddr, SocketAddr}, str::FromStr, }; #[derive(Clone, Debug)] struct Addr { addr: IpAddr, port: Option<u16>, } impl std::fmt::Display for Addr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let ipv = if self.addr.is_ipv4() { "4" } else { "6" }; let hex = match self.addr { IpAddr::V4(addr) => u32::from(addr) as u128, IpAddr::V6(addr) => u128::from(addr), }; match self.port { Some(p) => write!( f, "address: {}, port: {}, hex: {:x} (IPv{})", self.addr, p, hex, ipv ), None => write!( f, "address: {}, port: N/A, hex: {:x} (IPv{}) ", self.addr, hex, ipv ), } } } impl FromStr for Addr { type Err = (); fn from_str(s: &str) -> Result<Self, Self::Err> { if let Ok(addr) = s.parse::<IpAddr>() { Ok(Self { addr, port: None }) } else if let Ok(sock) = s.parse::<SocketAddr>() { Ok(Self { addr: sock.ip(), port: Some(sock.port()), }) } else { Err(()) } } } fn print_addr(s: &str) { match s.parse::<Addr>() { Ok(addr) => println!("{}: {}", s, addr), _ => println!("{} not a valid address", s), } } fn main() { [ "127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", ] .iter() .cloned() .for_each(print_addr); }
469Parse an IP Address
15rust
nh7i4
object IPparser extends App { def myCases = Map( "http:" -> IPInvalidAddressComponents(remark = "No match at all: 'http:'."), "http:
469Parse an IP Address
16scala
tpkfb
use strict; use warnings; use feature 'say'; my $number = '[+-/$]?(?:\.\d+|\d+(?:\.\d*)?)'; my $operator = '[-+*/^]'; my @tests = ('1 2 + 3 4 + ^ 5 6 + ^', '3 4 2 * 1 5 - 2 3 ^ ^ / +'); for (@tests) { my(@elems,$n); $n = -1; while ( s/ \s* (?<left>$number) \s+ (?<right>$number) \s+ (?<op>$operator) (?:\s+|$) / ' '.('$'.++$n).' ' /ex) { $elems[$n] = "($+{left}$+{op}$+{right})" } while ( s/ (\$)(\d+) / $elems[$2] /ex ) { say } say '=>' . substr($_,2,-2)."\n"; }
472Parsing/RPN to infix conversion
2perl
mxpyz
null
471Parsing/Shunting-yard algorithm
1lua
8ru0e
import static java.lang.System.out; import java.util.List; import java.util.function.Function; import java.util.stream.*; import static java.util.stream.Collectors.toList; import static java.util.stream.IntStream.range; public class PascalMatrix { static int binomialCoef(int n, int k) { int result = 1; for (int i = 1; i <= k; i++) result = result * (n - i + 1) / i; return result; } static List<IntStream> pascal(int n, Function<Integer, IntStream> f) { return range(0, n).mapToObj(i -> f.apply(i)).collect(toList()); } static List<IntStream> pascalUpp(int n) { return pascal(n, i -> range(0, n).map(j -> binomialCoef(j, i))); } static List<IntStream> pascalLow(int n) { return pascal(n, i -> range(0, n).map(j -> binomialCoef(i, j))); } static List<IntStream> pascalSym(int n) { return pascal(n, i -> range(0, n).map(j -> binomialCoef(i + j, i))); } static void print(String label, List<IntStream> result) { out.println("\n" + label); for (IntStream row : result) { row.forEach(i -> out.printf("%2d ", i)); System.out.println(); } } public static void main(String[] a) { print("Upper: ", pascalUpp(5)); print("Lower: ", pascalLow(5)); print("Symmetric:", pascalSym(5)); } }
474Pascal matrix generation
9java
dk5n9
sub fs(&) { my $func = shift; sub { map $func->($_), @_ } } sub double($) { shift() * 2 } sub square($) { shift() ** 2 } my $fs_double = fs(\&double); my $fs_square = fs(\&square); my @s = 0 .. 3; print "fs_double(@s): @{[ $fs_double->(@s) ]}\n"; print "fs_square(@s): @{[ $fs_square->(@s) ]}\n"; @s = (2, 4, 6, 8); print "fs_double(@s): @{[ $fs_double->(@s) ]}\n"; print "fs_square(@s): @{[ $fs_square->(@s) ]}\n";
468Partial function application
2perl
wv2e6
import random lowercase = 'abcdefghijklmnopqrstuvwxyz' uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' digits = '0123456789' punctuation = '!password length={} is too short,minimum length=4") return '' choice = random.SystemRandom().choice while True: password_chars = [ choice(lowercase), choice(uppercase), choice(digits), choice(punctuation) ] + random.sample(allowed, length-4) if (not readable or all(c not in visually_similar for c in password_chars)): random.SystemRandom().shuffle(password_chars) return ''.join(password_chars) def password_generator(length, qty=1, readable=True): for i in range(qty): print(new_password(length, readable))
463Password generator
3python
nh1iz
use ntheory qw/factor vecmax/; use threads; use threads::shared; my @results :shared; my $tnum = 0; $_->join() for map { threads->create('tfactor', $tnum++, $_) } (qw/576460752303423487 576460752303423487 576460752303423487 112272537195293 115284584522153 115280098190773 115797840077099 112582718962171 299866111963290359/); my $lmf = vecmax( map { $_->[1] } @results ); print "Largest minimal factor of $lmf found in:\n"; print " $_->[0] = [@$_[1..$ sub tfactor { my($tnum, $n) = @_; push @results, shared_clone([$n, factor($n)]); }
473Parallel calculations
2perl
cs19a
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PalindromicGapfulNumbers { public static void main(String[] args) { System.out.println("First 20 palindromic gapful numbers ending in:"); displayMap(getPalindromicGapfulEnding(20, 20)); System.out.printf("%nLast 15 of first 100 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(15, 100)); System.out.printf("%nLast 10 of first 1000 palindromic gapful numbers ending in:%n"); displayMap(getPalindromicGapfulEnding(10, 1000)); } private static void displayMap(Map<Integer,List<Long>> map) { for ( int key = 1 ; key <= 9 ; key++ ) { System.out.println(key + ": " + map.get(key)); } } public static Map<Integer,List<Long>> getPalindromicGapfulEnding(int countReturned, int firstHowMany) { Map<Integer,List<Long>> map = new HashMap<>(); Map<Integer,Integer> mapCount = new HashMap<>(); for ( int i = 1 ; i <= 9 ; i++ ) { map.put(i, new ArrayList<>()); mapCount.put(i, 0); } boolean notPopulated = true; for ( long n = 101 ; notPopulated ; n = nextPalindrome(n) ) { if ( isGapful(n) ) { int index = (int) (n % 10); if ( mapCount.get(index) < firstHowMany ) { map.get(index).add(n); mapCount.put(index, mapCount.get(index) + 1); if ( map.get(index).size() > countReturned ) { map.get(index).remove(0); } } boolean finished = true; for ( int i = 1 ; i <= 9 ; i++ ) { if ( mapCount.get(i) < firstHowMany ) { finished = false; break; } } if ( finished ) { notPopulated = false; } } } return map; } public static boolean isGapful(long n) { String s = Long.toString(n); return n % Long.parseLong("" + s.charAt(0) + s.charAt(s.length()-1)) == 0; } public static int length(long n) { int length = 0; while ( n > 0 ) { length += 1; n /= 10; } return length; } public static long nextPalindrome(long n) { int length = length(n); if ( length % 2 == 0 ) { length /= 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/10)); } return Long.parseLong(n + reverse(n)); } length = (length - 1) / 2; while ( length > 0 ) { n /= 10; length--; } n += 1; if ( powerTen(n) ) { return Long.parseLong(n + reverse(n/100)); } return Long.parseLong(n + reverse(n/10)); } private static boolean powerTen(long n) { while ( n > 9 && n % 10 == 0 ) { n /= 10; } return n == 1; } private static String reverse(long n) { return (new StringBuilder(n + "")).reverse().toString(); } }
480Palindromic gapful numbers
9java
7zerj
(defn pangram? [s] (let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")] (= (->> s .toLowerCase (filter letters) (into #{})) letters)))
482Pangram checker
6clojure
rtpg2
(() => { 'use strict';
474Pascal matrix generation
10javascript
6ej38
passwords <- function(nl = 8, npw = 1, help = FALSE) { if (help) return("gives npw passwords with nl characters each") if (nl < 4) nl <- 4 spch <- c("!", "\"", " for(i in 1:npw) { pw <- c(sample(letters, 1), sample(LETTERS, 1), sample(0:9, 1), sample(spch, 1)) pw <- c(pw, sample(c(letters, LETTERS, 0:9, spch), nl-4, replace = TRUE)) cat(sample(pw), "\n", sep = "") } } set.seed(123) passwords(help = TRUE) passwords(8) passwords(14, 5)
463Password generator
13r
0ghsg
import multiprocessing from hashlib import sha256 h1 = bytes().fromhex() h2 = bytes().fromhex() h3 = bytes().fromhex() def brute(firstletterascii: int): global h1, h2, h3 letters = bytearray(5) letters[0] = firstletterascii for letters[1] in range(97, 97 + 26): for letters[2] in range(97, 97 + 26): for letters[3] in range(97, 97 + 26): for letters[4] in range(97, 97 + 26): digest = sha256(letters).digest() if digest == h1 or digest == h2 or digest == h3: password = .join(chr(x) for x in letters) print(password + + digest.hex()) return 0 def main(): with multiprocessing.Pool() as p: p.map(brute, range(97, 97 + 26)) if __name__ == : main()
476Parallel brute force
3python
yw76q
package main import ( "fmt" "math" "strconv" "strings" ) var input = "3 4 2 * 1 5 - 2 3 ^ ^ / +" func main() { fmt.Printf("For postfix%q\n", input) fmt.Println("\nToken Action Stack") var stack []float64 for _, tok := range strings.Fields(input) { action := "Apply op to top of stack" switch tok { case "+": stack[len(stack)-2] += stack[len(stack)-1] stack = stack[:len(stack)-1] case "-": stack[len(stack)-2] -= stack[len(stack)-1] stack = stack[:len(stack)-1] case "*": stack[len(stack)-2] *= stack[len(stack)-1] stack = stack[:len(stack)-1] case "/": stack[len(stack)-2] /= stack[len(stack)-1] stack = stack[:len(stack)-1] case "^": stack[len(stack)-2] = math.Pow(stack[len(stack)-2], stack[len(stack)-1]) stack = stack[:len(stack)-1] default: action = "Push num onto top of stack" f, _ := strconv.ParseFloat(tok, 64) stack = append(stack, f) } fmt.Printf("%3s %-26s %v\n", tok, action, stack) } fmt.Println("\nThe final value is", stack[0]) }
479Parsing/RPN calculator algorithm
0go
9qrmt
try: import psyco psyco.full() except ImportError: pass MAX_N = 300 BRANCH = 4 ra = [0] * MAX_N unrooted = [0] * MAX_N def tree(br, n, l, sum = 1, cnt = 1): global ra, unrooted, MAX_N, BRANCH for b in xrange(br + 1, BRANCH + 1): sum += n if sum >= MAX_N: return if l * 2 >= sum and b >= BRANCH: return if b == br + 1: c = ra[n] * cnt else: c = c * (ra[n] + (b - br - 1)) / (b - br) if l * 2 < sum: unrooted[sum] += c if b < BRANCH: ra[sum] += c; for m in range(1, n): tree(b, m, l, sum, c) def bicenter(s): global ra, unrooted if not (s & 1): aux = ra[s / 2] unrooted[s] += aux * (aux + 1) / 2 def main(): global ra, unrooted, MAX_N ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1 for n in xrange(1, MAX_N): tree(0, n, n) bicenter(n) print % (n, unrooted[n]) main()
478Paraffins
3python
6e43w
import 'dart:io'; pascal(n) { if(n<=0) print("Not defined"); else if(n==1) print(1); else { List<List<int>> matrix = new List<List<int>>(); matrix.add(new List<int>()); matrix.add(new List<int>()); matrix[0].add(1); matrix[1].add(1); matrix[1].add(1); for (var i = 2; i < n; i++) { List<int> list = new List<int>(); list.add(1); for (var j = 1; j<i; j++) { list.add(matrix[i-1][j-1]+matrix[i-1][j]); } list.add(1); matrix.add(list); } for(var i=0; i<n; i++) { for(var j=0; j<=i; j++) { stdout.write(matrix[i][j]); stdout.write(' '); } stdout.write('\n'); } } } void main() { pascal(0); pascal(1); pascal(3); pascal(6); }
481Pascal's triangle
18dart
dkmnj
prec_dict = {'^':4, '*':3, '/':3, '+':2, '-':2} assoc_dict = {'^':1, '*':0, '/':0, '+':0, '-':0} class Node: def __init__(self,x,op,y=None): self.precedence = prec_dict[op] self.assocright = assoc_dict[op] self.op = op self.x,self.y = x,y def __str__(self): if self.y == None: return '%s(%s)'%(self.op,str(self.x)) str_y = str(self.y) if self.y < self or \ (self.y == self and self.assocright) or \ (str_y[0] is '-' and self.assocright): str_y = '(%s)'%str_y str_x = str(self.x) str_op = self.op if self.op is '+' and not isinstance(self.x, Node) and str_x[0] is '-': str_x = str_x[1:] str_op = '-' elif self.op is '-' and not isinstance(self.x, Node) and str_x[0] is '-': str_x = str_x[1:] str_op = '+' elif self.x < self or \ (self.x == self and not self.assocright and \ getattr(self.x, 'op', 1) != getattr(self, 'op', 2)): str_x = '(%s)'%str_x return ' '.join([str_y, str_op, str_x]) def __repr__(self): return 'Node(%s,%s,%s)'%(repr(self.x), repr(self.op), repr(self.y)) def __lt__(self, other): if isinstance(other, Node): return self.precedence < other.precedence return self.precedence < prec_dict.get(other,9) def __gt__(self, other): if isinstance(other, Node): return self.precedence > other.precedence return self.precedence > prec_dict.get(other,9) def __eq__(self, other): if isinstance(other, Node): return self.precedence == other.precedence return self.precedence > prec_dict.get(other,9) def rpn_to_infix(s, VERBOSE=False): if VERBOSE: print('TOKEN STACK') stack=[] for token in s.replace('^','^').split(): if token in prec_dict: stack.append(Node(stack.pop(),token,stack.pop())) else: stack.append(token) if VERBOSE: print(token+' '*(7-len(token))+repr(stack)) return str(stack[0]) strTest = strResult = rpn_to_infix(strTest, VERBOSE=False) print (,strTest) print (,strResult) print() strTest = strResult = rpn_to_infix(strTest, VERBOSE=False) print (,strTest) print (,strResult)
472Parsing/RPN to infix conversion
3python
9q1mf
def evaluateRPN(expression) { def stack = [] as Stack def binaryOp = { action -> return { action.call(stack.pop(), stack.pop()) } } def actions = [ '+': binaryOp { a, b -> b + a }, '-': binaryOp { a, b -> b - a }, '*': binaryOp { a, b -> b * a }, '/': binaryOp { a, b -> b / a }, '^': binaryOp { a, b -> b ** a } ] expression.split(' ').each { item -> def action = actions[item] ?: { item as BigDecimal } stack.push(action.call()) println "$item: $stack" } assert stack.size() == 1: "Unbalanced Expression: $expression ($stack)" stack.pop() }
479Parsing/RPN calculator algorithm
7groovy
z1vt5
my %prec = ( '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1 ); my %assoc = ( '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left' ); sub shunting_yard { my @inp = split ' ', $_[0]; my @ops; my @res; my $report = sub { printf "%25s %-7s%10s%s\n", "@res", "@ops", $_[0], "@inp" }; my $shift = sub { $report->("shift @_"); push @ops, @_ }; my $reduce = sub { $report->("reduce @_"); push @res, @_ }; while (@inp) { my $token = shift @inp; if ( $token =~ /\d/ ) { $reduce->($token) } elsif ( $token eq '(' ) { $shift->($token) } elsif ( $token eq ')' ) { while ( @ops and "(" ne ( my $x = pop @ops ) ) { $reduce->($x) } } else { my $newprec = $prec{$token}; while (@ops) { my $oldprec = $prec{ $ops[-1] }; last if $newprec > $oldprec; last if $newprec == $oldprec and $assoc{$token} eq 'right'; $reduce->( pop @ops ); } $shift->($token); } } $reduce->( pop @ops ) while @ops; @res; } local $, = " "; print shunting_yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3';
471Parsing/Shunting-yard algorithm
2perl
5n0u2
from functools import partial def fs(f, s): return [f(value) for value in s] def f1(value): return value * 2 def f2(value): return value ** 2 fsf1 = partial(fs, f1) fsf2 = partial(fs, f2) s = [0, 1, 2, 3] assert fs(f1, s) == fsf1(s) assert fs(f2, s) == fsf2(s) s = [2, 4, 6, 8] assert fs(f1, s) == fsf1(s) assert fs(f2, s) == fsf2(s)
468Partial function application
3python
xuvwr
null
476Parallel brute force
15rust
csk9z
import java.security.MessageDigest import scala.collection.parallel.immutable.ParVector object EncryptionCracker { def main(args: Array[String]): Unit = { val hash1 = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad" val hash2 = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b" val hash3 = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f" val charSet = ('a' to 'z').toVector val num = 5 for(tmp <- List(hash1, hash2, hash3)){ println(tmp) crack(tmp, charSet, num) match{ case Some(s) => println(s"String: $s\n") case None => println("Failed\n") } } } def crack(hash: String, charSet: Vector[Char], num: Int): Option[String] = { val perms = charSet .flatMap(c => Vector.fill(num)(c)).combinations(num)
476Parallel brute force
16scala
vo12s
from concurrent import futures from math import floor, sqrt NUMBERS = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419] def lowest_factor(n, _start=3): if n% 2 == 0: return 2 search_max = int(floor(sqrt(n))) + 1 for i in range(_start, search_max, 2): if n% i == 0: return i return n def prime_factors(n, lowest): pf = [] while n > 1: pf.append(lowest) n lowest = lowest_factor(n, max(lowest, 3)) return pf def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): with futures.ProcessPoolExecutor() as executor: low_factor, number = max( (l, f) for l, f in zip(executor.map(lowest_factor, NUMBERS), NUMBERS) ) all_factors = prime_factors(number, low_factor) return number, all_factors def main(): print('For these numbers:') print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) print(' The one with the largest minimum prime factor is {}:'.format(number)) print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main()
473Parallel calculations
3python
l0acv