code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
calcRPN :: String -> [Double] calcRPN = foldl interprete [] . words interprete s x | x `elem` ["+","-","*","/","^"] = operate x s | otherwise = read x:s where operate op (x:y:s) = case op of "+" -> x + y:s "-" -> y - x:s "*" -> x * y:s "/" -> y / x:s "^" -> y ** x:s
479Parsing/RPN calculator algorithm
8haskell
bm0k2
null
474Pascal matrix generation
11kotlin
0gcsf
partially.apply <- function(f, ...) { capture <- list(...) function(...) { do.call(f, c(capture, list(...))) } } fs <- function(f, ...) sapply(list(...), f) f1 <- function(x) 2*x f2 <- function(x) x^2 fsf1 <- partially.apply(fs, f1) fsf2 <- partially.apply(fs, f2) fsf1(0:3) fsf2(0:3) fsf1(seq(2,8,2)) fsf2(seq(2,8,2))
468Partial function application
13r
1c9pn
import Foundation import CryptoKit extension String { func hexdata() -> Data { Data(stride(from: 0, to: count, by: 2).map { let a = index(startIndex, offsetBy: $0) let b = index(after: a) return UInt8(self[a ... b], radix: 16)! }) } } DispatchQueue.concurrentPerform(iterations: 26) { (a) in let goal1 = "1115dd800feaacefdf481f1f9070374a2a81e27880f187396db67958b207cbad".hexdata() let goal2 = "3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b".hexdata() let goal3 = "74e1bb62f8dabb8125a58852b63bdf6eaef667cb56ac7f7cdba6d7305c50a22f".hexdata() var letters: [UInt8] = [(UInt8)(a + 97), 0, 0, 0, 0] for b: UInt8 in 97...122 { letters[1] = b for c: UInt8 in 97...122 { letters[2] = c for d: UInt8 in 97...122 { letters[3] = d for e: UInt8 in 97...122 { letters[4] = e let digest = SHA256.hash(data: letters) if digest == goal1 || digest == goal2 || digest == goal3 { let password = String(bytes: letters, encoding: .ascii)! let hexhash = digest.map { String(format: "%02x", $0) }.joined() print("\(password) => \(hexhash)") } } } } } }
476Parallel brute force
17swift
mxjyk
MAX_N = 500 BRANCH = 4 def tree(br, n, l=n, sum=1, cnt=1) for b in br+1 .. BRANCH sum += n return if sum >= MAX_N return if l * 2 >= sum and b >= BRANCH if b == br + 1 c = $ra[n] * cnt else c = c * ($ra[n] + (b - br - 1)) / (b - br) end $unrooted[sum] += c if l * 2 < sum next if b >= BRANCH $ra[sum] += c (1...n).each {|m| tree(b, m, l, sum, c)} end end def bicenter(s) return if s.odd? aux = $ra[s / 2] $unrooted[s] += aux * (aux + 1) / 2 end $ra = [0] * MAX_N $unrooted = [0] * MAX_N $ra[0] = $ra[1] = $unrooted[0] = $unrooted[1] = 1 for n in 1...MAX_N tree(0, n) bicenter(n) puts % [n, $unrooted[n]] end
478Paraffins
14ruby
mxryj
function factorial (n) local f = 1 for i = 2, n do f = f * i end return f end function binomial (n, k) if k > n then return 0 end return factorial(n) / (factorial(k) * factorial(n - k)) end function pascalMatrix (form, size) local matrix = {} for row = 1, size do matrix[row] = {} for col = 1, size do if form == "upper" then matrix[row][col] = binomial(col - 1, row - 1) end if form == "lower" then matrix[row][col] = binomial(row - 1, col - 1) end if form == "symmetric" then matrix[row][col] = binomial(row + col - 2, col - 1) end end end matrix.form = form:sub(1, 1):upper() .. form:sub(2, -1) return matrix end function show (mat) print(mat.form .. ":") for i = 1, #mat do for j = 1, #mat[i] do io.write(mat[i][j] .. "\t") end print() end print() end for _, form in pairs({"upper", "lower", "symmetric"}) do show(pascalMatrix(form, 5)) end
474Pascal matrix generation
1lua
8rl0e
rpn = RPNExpression.new() infix = rpn.to_infix ruby = rpn.to_ruby
472Parsing/RPN to infix conversion
14ruby
l0ecl
null
473Parallel calculations
15rust
uixvj
import java.util.LinkedList; public class RPN{ public static void main(String[] args) { evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +"); } private static void evalRPN(String expr){ LinkedList<Double> stack = new LinkedList<Double>(); System.out.println("Input\tOperation\tStack after"); for (String token: expr.split("\\s")){ System.out.print(token + "\t"); if (token.equals("*")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand * secondOperand); } else if (token.equals("/")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand / secondOperand); } else if (token.equals("-")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand - secondOperand); } else if (token.equals("+")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(firstOperand + secondOperand); } else if (token.equals("^")) { System.out.print("Operate\t\t"); double secondOperand = stack.pop(); double firstOperand = stack.pop(); stack.push(Math.pow(firstOperand, secondOperand)); } else { System.out.print("Push\t\t"); try { stack.push(Double.parseDouble(token+"")); } catch (NumberFormatException e) { System.out.println("\nError: invalid token " + token); return; } } System.out.println(stack); } if (stack.size() > 1) { System.out.println("Error, too many operands: " + stack); return; } System.out.println("Final answer: " + stack.pop()); } }
479Parsing/RPN calculator algorithm
9java
gfa4m
use strict; use warnings; use feature 'say'; use constant Inf => 1e10; sub is_p_gapful { my($d,$n) = @_; return '' unless 0 == $n % 11; my @digits = split //, $n; $d eq $digits[0] and (0 == $n % ($digits[0].$digits[-1])) and $n eq join '', reverse @digits; } for ([1, 20], [86, 15]) { my($offset, $count) = @$_; say "Palindromic gapful numbers starting at $offset:"; for my $d ('1'..'9') { my $n = 0; my $out = "$d: "; $out .= do { $n+1 < $count+$offset ? (is_p_gapful($d,$_) and ++$n and $n >= $offset and "$_ ") : last } for 100 .. Inf; say $out } say '' }
480Palindromic gapful numbers
2perl
8r30w
from collections import namedtuple from pprint import pprint as pp OpInfo = namedtuple('OpInfo', 'prec assoc') L, R = 'Left Right'.split() ops = { '^': OpInfo(prec=4, assoc=R), '*': OpInfo(prec=3, assoc=L), '/': OpInfo(prec=3, assoc=L), '+': OpInfo(prec=2, assoc=L), '-': OpInfo(prec=2, assoc=L), '(': OpInfo(prec=9, assoc=L), ')': OpInfo(prec=0, assoc=L), } NUM, LPAREN, RPAREN = 'NUMBER ( )'.split() def get_input(inp = None): 'Inputs an expression and returns list of (TOKENTYPE, tokenvalue)' if inp is None: inp = input('expression: ') tokens = inp.strip().split() tokenvals = [] for token in tokens: if token in ops: tokenvals.append((token, ops[token])) else: tokenvals.append((NUM, token)) return tokenvals def shunting(tokenvals): outq, stack = [], [] table = ['TOKEN,ACTION,RPN OUTPUT,OP STACK,NOTES'.split(',')] for token, val in tokenvals: note = action = '' if token is NUM: action = 'Add number to output' outq.append(val) table.append( (val, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) elif token in ops: t1, (p1, a1) = token, val v = t1 note = 'Pop ops from stack to output' while stack: t2, (p2, a2) = stack[-1] if (a1 == L and p1 <= p2) or (a1 == R and p1 < p2): if t1 != RPAREN: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: break else: if t2 != LPAREN: stack.pop() action = '(Pop op)' outq.append(t2) else: stack.pop() action = '(Pop & discard )' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) break table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' else: note = '' break note = '' note = '' if t1 != RPAREN: stack.append((token, val)) action = 'Push op token to stack' else: action = 'Discard ' table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) note = 'Drain stack to output' while stack: v = '' t2, (p2, a2) = stack[-1] action = '(Pop op)' stack.pop() outq.append(t2) table.append( (v, action, ' '.join(outq), ' '.join(s[0] for s in stack), note) ) v = note = '' return table if __name__ == '__main__': infix = '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' print( 'For infix expression:%r\n'% infix ) rp = shunting(get_input(infix)) maxcolwidths = [len(max(x, key=len)) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output RPN is:%r'% rp[-1][2])
471Parsing/Shunting-yard algorithm
3python
4d85k
object Paraffins extends App { val (nMax, nBranches) = (250, 4) val rooted, unrooted = Array.tabulate(nMax + 1)(i => if (i < 2) BigInt(1) else BigInt(0)) val (unrooted, c) = (rooted.clone(), new Array[BigInt](nBranches)) for (n <- 1 to nMax) { def tree(br: Int, n: Int, l: Int, inSum: Int, cnt: BigInt): Unit = { var sum = inSum for (b <- br + 1 to nBranches) { sum += n if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return if (b == br + 1) c(br) = rooted(n) * cnt else { c(br) = c(br) * (rooted(n) + BigInt(b - br - 1)) c(br) = c(br) / BigInt(b - br) } if (l * 2 < sum) unrooted(sum) = unrooted(sum) + c(br) if (b < nBranches) rooted(sum) = rooted(sum) + c(br) for (m <- n - 1 to 1 by -1) tree(b, m, l, sum, c(br)) } } def bicenter(s: Int): Unit = if ((s & 1) == 0) { val halves = rooted(s / 2) unrooted(s) = unrooted(s) + ((halves + BigInt(1)) * halves >> 1) } tree(0, n, n, 1, BigInt(1)) bicenter(n) println(f"$n%3d: ${unrooted(n)}%s") } }
478Paraffins
16scala
28klb
ARRS = [(..).to_a, (..).to_a, (..).to_a, %q(! quote to reset clumsy code colorizer ALL = ARRS.flatten def generate_pwd(size, num) raise ArgumentError, unless size >= ARRS.size num.times.map do arr = ARRS.map(&:sample) (size - ARRS.size).times{ arr << ALL.sample} arr.shuffle.join end end puts generate_pwd(8,3)
463Password generator
14ruby
fbedr
const e = '3 4 2 * 1 5 - 2 3 ^ ^ / +'; const s = [], tokens = e.split(' '); for (const t of tokens) { const n = Number(t); if (!isNaN(n)) { s.push(n); } else { if (s.length < 2) { throw new Error(`${t}: ${s}: insufficient operands.`); } const o2 = s.pop(), o1 = s.pop(); switch (t) { case '+': s.push(o1 + o2); break; case '-': s.push(o1 - o2); break; case '*': s.push(o1 * o2); break; case '/': s.push(o1 / o2); break; case '^': s.push(Math.pow(o1, o2)); break; default: throw new Error(`Unrecognized operator: [${t}]`); } } console.log(`${t}: ${s}`); } if (s.length > 1) { throw new Error(`${s}: insufficient operators.`); }
479Parsing/RPN calculator algorithm
10javascript
kyshq
fs = proc { |f, s| s.map &f } f1 = proc { |n| n * 2 } f2 = proc { |n| n ** 2 } fsf1 = fs.curry[f1] fsf2 = fs.curry[f2] [0..3, (2..8).step(2)].each do |e| p fsf1[e] p fsf2[e] end
468Partial function application
14ruby
s45qw
import BigInt import Foundation extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0? 2: 3 while q <= maxQ && self% q!= 0 { q = step(d) d += 1 } return q <= maxQ? [q] + (self / q).primeDecomposition(): [self] } } let numbers = [ 112272537195293, 112582718962171, 112272537095293, 115280098190773, 115797840077099, 1099726829285419, 1275792312878611, BigInt("64921987050997300559") ] func findLargestMinFactor<T: BinaryInteger>(for nums: [T], then: @escaping ((n: T, factors: [T])) -> ()) { let waiter = DispatchSemaphore(value: 0) let lock = DispatchSemaphore(value: 1) var factors = [(n: T, factors: [T])]() DispatchQueue.concurrentPerform(iterations: nums.count) {i in let n = nums[i] print("Factoring \(n)") let nFacs = n.primeDecomposition().sorted() print("Factored \(n)") lock.wait() factors.append((n, nFacs)) if factors.count == nums.count { waiter.signal() } lock.signal() } waiter.wait() then(factors.sorted(by: { $0.factors.first! > $1.factors.first! }).first!) } findLargestMinFactor(for: numbers) {res in let (n, factors) = res print("Number with largest min prime factor: \(n); factors: \(factors)") exit(0) } dispatchMain()
473Parallel calculations
17swift
28elj
null
479Parsing/RPN calculator algorithm
11kotlin
28hli
def fs[X](f:X=>X)(s:Seq[X]) = s map f def f1(x:Int) = x * 2 def f2(x:Int) = x * x def fsf[X](f:X=>X) = fs(f) _ val fsf1 = fsf(f1)
468Partial function application
16scala
ij7ox
use rand::distributions::Alphanumeric; use rand::prelude::IteratorRandom; use rand::{thread_rng, Rng}; use std::iter; use std::process; use structopt::StructOpt; const OTHER_VALUES: &str = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~";
463Password generator
15rust
tpwfd
from itertools import count from pprint import pformat import re import heapq def pal_part_gen(odd=True): for i in count(1): fwd = str(i) rev = fwd[::-1][1:] if odd else fwd[::-1] yield int(fwd + rev) def pal_ordered_gen(): yield from heapq.merge(pal_part_gen(odd=True), pal_part_gen(odd=False)) def is_gapful(x): return (x% (int(str(x)[0]) * 10 + (x% 10)) == 0) if __name__ == '__main__': start = 100 for mx, last in [(20, 20), (100, 15), (1_000, 10)]: print(f f) bin = {i: [] for i in range(1, 10)} gen = (i for i in pal_ordered_gen() if i >= start and is_gapful(i)) while any(len(val) < mx for val in bin.values()): g = next(gen) val = bin[g% 10] if len(val) < mx: val.append(g) b = {k:v[-last:] for k, v in bin.items()} txt = pformat(b, width=220) print('', re.sub(r, '', txt))
480Palindromic gapful numbers
3python
o7681
object makepwd extends App { def newPassword( salt:String = "", length:Int = 13, strong:Boolean = true ) = { val saltHash = salt.hashCode & ~(1 << 31) import java.util.Calendar._ val cal = java.util.Calendar.getInstance() val rand = new scala.util.Random((cal.getTimeInMillis+saltHash).toLong) val lower = ('a' to 'z').mkString val upper = ('A' to 'Z').mkString val nums = ('0' to '9').mkString val strongs = "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" val unwanted = if( strong ) "" else "0Ol" val pool = (lower + upper + nums + (if( strong ) strongs else "")). filterNot( c => unwanted.contains(c) ) val pwdStream = Stream.continually( (for( n <- 1 to length; c = pool(rand.nextInt(pool.length) ) ) yield c).mkString )
463Password generator
16scala
6es31
rpn = RPNExpression.from_infix()
471Parsing/Shunting-yard algorithm
14ruby
rtigs
type Number = f64; #[derive(Debug, Copy, Clone, PartialEq)] struct Operator { token: char, operation: fn(Number, Number) -> Number, precedence: u8, is_left_associative: bool, } #[derive(Debug, Clone, PartialEq)] enum Token { Digit(Number), Operator(Operator), LeftParen, RightParen, } impl Operator { fn new_token( token: char, precedence: u8, is_left_associative: bool, operation: fn(Number, Number) -> Number, ) -> Token { Token::Operator(Operator { token: token, operation: operation, precedence: precedence, is_left_associative, }) } fn apply(&self, x: Number, y: Number) -> Number { (self.operation)(x, y) } } trait Stack<T> { fn top(&self) -> Option<T>; } impl<T: Clone> Stack<T> for Vec<T> { fn top(&self) -> Option<T> { if self.is_empty() { return None; } self.last().cloned() } } fn lex_token(input: char) -> Result<Token, char> { let ret = match input { '0'...'9' => Token::Digit(input.to_digit(10).unwrap() as Number), '+' => Operator::new_token('+', 1, true, |x, y| x + y), '-' => Operator::new_token('-', 1, true, |x, y| x - y), '*' => Operator::new_token('*', 2, true, |x, y| x * y), '/' => Operator::new_token('/', 2, true, |x, y| x / y), '^' => Operator::new_token('^', 3, false, |x, y| x.powf(y)), '(' => Token::LeftParen, ')' => Token::RightParen, _ => return Err(input), }; Ok(ret) } fn lex(input: String) -> Result<Vec<Token>, char> { input .chars() .filter(|c|!c.is_whitespace()) .map(lex_token) .collect() } fn tilt_until(operators: &mut Vec<Token>, output: &mut Vec<Token>, stop: Token) -> bool { while let Some(token) = operators.pop() { if token == stop { return true; } output.push(token) } false } fn shunting_yard(tokens: Vec<Token>) -> Result<Vec<Token>, String> { let mut output: Vec<Token> = Vec::new(); let mut operators: Vec<Token> = Vec::new(); for token in tokens { match token { Token::Digit(_) => output.push(token), Token::LeftParen => operators.push(token), Token::Operator(operator) => { while let Some(top) = operators.top() { match top { Token::LeftParen => break, Token::Operator(top_op) => { let p = top_op.precedence; let q = operator.precedence; if (p > q) || (p == q && operator.is_left_associative) { output.push(operators.pop().unwrap()); } else { break; } } _ => unreachable!("{:?} must not be on operator stack", token), } } operators.push(token); } Token::RightParen => { if!tilt_until(&mut operators, &mut output, Token::LeftParen) { return Err(String::from("Mismatched ')'")); } } } } if tilt_until(&mut operators, &mut output, Token::LeftParen) { return Err(String::from("Mismatched '('")); } assert!(operators.is_empty()); Ok(output) } fn calculate(postfix_tokens: Vec<Token>) -> Result<Number, String> { let mut stack = Vec::new(); for token in postfix_tokens { match token { Token::Digit(number) => stack.push(number), Token::Operator(operator) => { if let Some(y) = stack.pop() { if let Some(x) = stack.pop() { stack.push(operator.apply(x, y)); continue; } } return Err(format!("Missing operand for operator '{}'", operator.token)); } _ => unreachable!("Unexpected token {:?} during calculation", token), } } assert!(stack.len() == 1); Ok(stack.pop().unwrap()) } fn run(input: String) -> Result<Number, String> { let tokens = match lex(input) { Ok(tokens) => tokens, Err(c) => return Err(format!("Invalid character: {}", c)), }; let postfix_tokens = match shunting_yard(tokens) { Ok(tokens) => tokens, Err(message) => return Err(message), }; calculate(postfix_tokens) }
471Parsing/Shunting-yard algorithm
15rust
7znrc
use warnings; use strict; use feature qw{ say }; sub upper { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = $x > $y ? 0 : ! $x || $x == $y ? 1 : $m[$x-1][$y-1] + $m[$x][$y-1]; } } return \@m } sub lower { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = $x < $y ? 0 : ! $x || $x == $y ? 1 : $m[$x-1][$y-1] + $m[$x-1][$y]; } } return \@m } sub symmetric { my ($i, $j) = @_; my @m; for my $x (0 .. $i - 1) { for my $y (0 .. $j - 1) { $m[$x][$y] = ! $x || ! $y ? 1 : $m[$x-1][$y] + $m[$x][$y-1]; } } return \@m } sub pretty { my $m = shift; for my $row (@$m) { say join ', ', @$row; } } pretty(upper(5, 5)); say '-' x 14; pretty(lower(5, 5)); say '-' x 14; pretty(symmetric(5, 5));
474Pascal matrix generation
2perl
5nxu2
local stack = {} function push( a ) table.insert( stack, 1, a ) end function pop() if #stack == 0 then return nil end return table.remove( stack, 1 ) end function writeStack() for i = #stack, 1, -1 do io.write( stack[i], " " ) end print() end function operate( a ) local s if a == "+" then push( pop() + pop() ) io.write( a .. "\tadd\t" ); writeStack() elseif a == "-" then s = pop(); push( pop() - s ) io.write( a .. "\tsub\t" ); writeStack() elseif a == "*" then push( pop() * pop() ) io.write( a .. "\tmul\t" ); writeStack() elseif a == "/" then s = pop(); push( pop() / s ) io.write( a .. "\tdiv\t" ); writeStack() elseif a == "^" then s = pop(); push( pop() ^ s ) io.write( a .. "\tpow\t" ); writeStack() elseif a == "%" then s = pop(); push( pop() % s ) io.write( a .. "\tmod\t" ); writeStack() else push( tonumber( a ) ) io.write( a .. "\tpush\t" ); writeStack() end end function calc( s ) local t, a = "", "" print( "\nINPUT", "OP", "STACK" ) for i = 1, #s do a = s:sub( i, i ) if a == " " then operate( t ); t = "" else t = t .. a end end if a ~= "" then operate( a ) end print( string.format( "\nresult:%.13f", pop() ) ) end
479Parsing/RPN calculator algorithm
1lua
vok2x
echo "enter a string" read input size=${ count=0 while (($count < $size)) do array[$count]=${input:$count:1} (( count+=1 )) done count=0 for ((i=0; i < $size; i+=1)) do if [ "${array[$i]}" == "${array[$size - $i - 1]}" ] then (( count += 1 )) fi done if (( $count == $size )) then echo "$input is a palindrome" fi
483Palindrome detection
4bash
28gl0
#include <stdlib.h> #include <time.h> void initRandom(const unsigned int seed){ if(seed==0){ srand((unsigned) time(NULL)); } else{ srand(seed); } } int getRand(const int upperBound){ return rand() % upperBound; }
463Password generator
17swift
dkanh
import Foundation
471Parsing/Shunting-yard algorithm
17swift
gfo49
def palindromesgapful(digit, pow) r1 = digit * (10**pow + 1) r2 = 10**pow * (digit + 1) nn = digit * 11 (r1...r2).select { |i| n = i.to_s; n == n.reverse && i % nn == 0 } end def digitscount(digit, count) pow = 2 nums = [] while nums.size < count nums += palindromesgapful(digit, pow) pow += 1 end nums[0...count] end count = 20 puts (1..9).each { |digit| print } count = 100 puts (1..9).each { |digit| print } count = 1000 puts (1..9).each { |digit| print }
480Palindromic gapful numbers
14ruby
nhmit
This version uses number->string then string->number conversions to create palindromes.
480Palindromic gapful numbers
15rust
dk9ny
from pprint import pprint as pp def pascal_upp(n): s = [[0] * n for _ in range(n)] s[0] = [1] * n for i in range(1, n): for j in range(i, n): s[i][j] = s[i-1][j-1] + s[i][j-1] return s def pascal_low(n): return [list(x) for x in zip(*pascal_upp(n))] def pascal_sym(n): s = [[1] * n for _ in range(n)] for i in range(1, n): for j in range(1, n): s[i][j] = s[i-1][j] + s[i][j-1] return s if __name__ == : n = 5 print() pp(pascal_upp(n)) print() pp(pascal_low(n)) print() pp(pascal_sym(n))
474Pascal matrix generation
3python
4dq5k
lower.pascal <- function(n) { a <- matrix(0, n, n) a[, 1] <- 1 if (n > 1) { for (i in 2:n) { j <- 2:i a[i, j] <- a[i - 1, j - 1] + a[i - 1, j] } } a } lower.pascal.alt <- function(n) { a <- matrix(0, n, n) a[, 1] <- 1 if (n > 1) { for (j in 2:n) { i <- j:n a[i, j] <- cumsum(a[i - 1, j - 1]) } } a } upper.pascal <- function(n) t(lower.pascal(n)) symm.pascal <- function(n) { a <- matrix(0, n, n) a[, 1] <- 1 for (i in 2:n) { a[, i] <- cumsum(a[, i - 1]) } a }
474Pascal matrix generation
13r
28alg
package main import "fmt" func main() { for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt.Println("No: ", s) } } } func pangram(s string) bool { var missing uint32 = (1 << 26) - 1 for _, c := range s { var index uint32 if 'a' <= c && c <= 'z' { index = uint32(c - 'a') } else if 'A' <= c && c <= 'Z' { index = uint32(c - 'A') } else { continue } missing &^= 1 << index if missing == 0 { return true } } return false }
482Pangram checker
0go
s4dqa
import Data.Char (toLower) import Data.List ((\\)) pangram :: String -> Bool pangram = null . (['a' .. 'z'] \\) . map toLower main = print $ pangram "How razorback-jumping frogs can level six piqued gymnasts!"
482Pangram checker
8haskell
9q5mo
require 'pp' ng = (g = 0..4).collect{[]} g.each{|i| g.each{|j| ng[i][j] = i==0? 1: j<i? 0: ng[i-1][j-1]+ng[i][j-1]}} pp ng; puts g.each{|i| g.each{|j| ng[i][j] = j==0? 1: i<j? 0: ng[i-1][j-1]+ng[i-1][j]}} pp ng; puts g.each{|i| g.each{|j| ng[i][j] = (i==0 or j==0)? 1: ng[i-1][j ]+ng[i][j-1]}} pp ng
474Pascal matrix generation
14ruby
rt0gs
use strict; use warnings; use feature 'say'; my $number = '[+-]?(?:\.\d+|\d+(?:\.\d*)?)'; my $operator = '[-+*/^]'; my @tests = ('3 4 2 * 1 5 - 2 3 ^ ^ / +'); for (@tests) { while ( s/ \s* ((?<left>$number)) \s+ ((?<right>$number)) \s+ ((?<op>$operator)) (?:\s+|$) / ' '.evaluate().' ' /ex ) {} say; } sub evaluate { (my $a = "($+{left})$+{op}($+{right})") =~ s/\^/**/; say $a; eval $a; }
479Parsing/RPN calculator algorithm
2perl
s4zq3
int palindrome(const char *s) { int i,l; l = strlen(s); for(i=0; i<l/2; i++) { if ( s[i] != s[l-i-1] ) return 0; } return 1; }
483Palindrome detection
5c
ui7v4
null
474Pascal matrix generation
16scala
kynhk
public class Pangram { public static boolean isPangram(String test){ for (char a = 'A'; a <= 'Z'; a++) if ((test.indexOf(a) < 0) && (test.indexOf((char)(a + 32)) < 0)) return false; return true; } public static void main(String[] args){ System.out.println(isPangram("the quick brown fox jumps over the lazy dog"));
482Pangram checker
9java
tp9f9
<?php function rpn($postFix){ $stack = Array(); echo ; $token = explode(, trim($postFix)); $count = count($token); for($i = 0 ; $i<$count;$i++) { echo $token[$i] .; $tokenNum = ; if (is_numeric($token[$i])) { echo ; array_push($stack,$token[$i]); } else { echo ; $secondOperand = end($stack); array_pop($stack); $firstOperand = end($stack); array_pop($stack); if ($token[$i] == ) array_push($stack,$firstOperand * $secondOperand); else if ($token[$i] == ) array_push($stack,$firstOperand / $secondOperand); else if ($token[$i] == ) array_push($stack,$firstOperand - $secondOperand); else if ($token[$i] == ) array_push($stack,$firstOperand + $secondOperand); else if ($token[$i] == ) array_push($stack,pow($firstOperand,$secondOperand)); else { die(); } } echo . implode(, $stack) . ; } return end($stack); } echo . rpn(); ?>
479Parsing/RPN calculator algorithm
12php
uibv5
function isPangram(s) { var letters = "zqxjkvbpygfwmucldrhsnioate"
482Pangram checker
10javascript
mxuyv
(defn palindrome? [s] (= s (clojure.string/reverse s)))
483Palindrome detection
6clojure
7zpr0
null
482Pangram checker
11kotlin
o7z8z
package main import "fmt" func printTriangle(n int) {
481Pascal's triangle
0go
1c0p5
require"lpeg" S, C = lpeg.S, lpeg.C function ispangram(s) return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26 end print(ispangram"waltz, bad nymph, for quick jigs vex") print(ispangram"bobby") print(ispangram"long sentence")
482Pangram checker
1lua
ij3ot
def pascal pascal = { n -> (n <= 1) ? [1]: [[0] + pascal(n - 1), pascal(n - 1) + [0]].transpose().collect { it.sum() } }
481Pascal's triangle
7groovy
j3e7o
def op_pow(stack): b = stack.pop(); a = stack.pop() stack.append( a ** b ) def op_mul(stack): b = stack.pop(); a = stack.pop() stack.append( a * b ) def op_div(stack): b = stack.pop(); a = stack.pop() stack.append( a / b ) def op_add(stack): b = stack.pop(); a = stack.pop() stack.append( a + b ) def op_sub(stack): b = stack.pop(); a = stack.pop() stack.append( a - b ) def op_num(stack, num): stack.append( num ) ops = { '^': op_pow, '*': op_mul, '/': op_div, '+': op_add, '-': op_sub, } def get_input(inp = None): 'Inputs an expression and returns list of tokens' if inp is None: inp = input('expression: ') tokens = inp.strip().split() return tokens def rpn_calc(tokens): stack = [] table = ['TOKEN,ACTION,STACK'.split(',')] for token in tokens: if token in ops: action = 'Apply op to top of stack' ops[token](stack) table.append( (token, action, ' '.join(str(s) for s in stack)) ) else: action = 'Push num onto top of stack' op_num(stack, eval(token)) table.append( (token, action, ' '.join(str(s) for s in stack)) ) return table if __name__ == '__main__': rpn = '3 4 2 * 1 5 - 2 3 ^ ^ / +' print( 'For RPN expression:%r\n'% rpn ) rp = rpn_calc(get_input(rpn)) maxcolwidths = [max(len(y) for y in x) for x in zip(*rp)] row = rp[0] print( ' '.join('{cell:^{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) for row in rp[1:]: print( ' '.join('{cell:<{width}}'.format(width=width, cell=cell) for (width, cell) in zip(maxcolwidths, row))) print('\n The final output value is:%r'% rp[-1][2])
479Parsing/RPN calculator algorithm
3python
0g3sq
zapWith :: (a -> a -> a) -> [a] -> [a] -> [a] zapWith f xs [] = xs zapWith f [] ys = ys zapWith f (x:xs) (y:ys) = f x y: zapWith f xs ys
481Pascal's triangle
8haskell
tpcf7
rpn = RPNExpression() value = rpn.eval
479Parsing/RPN calculator algorithm
14ruby
o7y8v
fn rpn(text: &str) -> f64 { let tokens = text.split_whitespace(); let mut stack: Vec<f64> = vec![]; println!("input operation stack"); for token in tokens { print!("{:^5} ", token); match token.parse() { Ok(num) => { stack.push(num); println!("push {:?}", stack); } Err(_) => { match token { "+" => { let b = stack.pop().expect("missing first operand"); let a = stack.pop().expect("missing second operand"); stack.push(a + b); } "-" => { let b = stack.pop().expect("missing first operand"); let a = stack.pop().expect("missing second operand"); stack.push(a - b); } "*" => { let b = stack.pop().expect("missing first operand"); let a = stack.pop().expect("missing second operand"); stack.push(a * b); } "/" => { let b = stack.pop().expect("missing first operand"); let a = stack.pop().expect("missing second operand"); stack.push(a / b); } "^" => { let b = stack.pop().expect("missing first operand"); let a = stack.pop().expect("missing second operand"); stack.push(a.powf(b)); } _ => panic!("unknown operator {}", token), } println!("calculate {:?}", stack); } } } stack.pop().unwrap_or(0.0) } fn main() { let text = "3 4 2 * 1 5 - 2 3 ^ ^ / +"; println!("\nresult: {}", rpn(text)); }
479Parsing/RPN calculator algorithm
15rust
ijmod
bool isPalindrome(String s){ for(int i = 0; i < s.length/2;i++){ if(s[i]!= s[(s.length-1) -i]) return false; } return true; }
483Palindrome detection
18dart
mxvyb
object RPN { val PRINT_STACK_CONTENTS: Boolean = true def main(args: Array[String]): Unit = { val result = evaluate("3 4 2 * 1 5 - 2 3 ^ ^ / +".split(" ").toList) println("Answer: " + result) } def evaluate(tokens: List[String]): Double = { import scala.collection.mutable.Stack val stack: Stack[Double] = new Stack[Double] for (token <- tokens) { if (isOperator(token)) token match { case "+" => stack.push(stack.pop + stack.pop) case "-" => val x = stack.pop; stack.push(stack.pop - x) case "*" => stack.push(stack.pop * stack.pop) case "/" => val x = stack.pop; stack.push(stack.pop / x) case "^" => val x = stack.pop; stack.push(math.pow(stack.pop, x)) case _ => throw new RuntimeException( s""""$token" is not an operator""") } else stack.push(token.toDouble) if (PRINT_STACK_CONTENTS) { print("Input: " + token) print(" Stack: ") for (element <- stack.seq.reverse) print(element + " "); println("") } } stack.pop } def isOperator(token: String): Boolean = { token match { case "+" => true; case "-" => true; case "*" => true; case "/" => true; case "^" => true case _ => false } } }
479Parsing/RPN calculator algorithm
16scala
fbld4
let opa = [ "^": (prec: 4, rAssoc: true), "*": (prec: 3, rAssoc: false), "/": (prec: 3, rAssoc: false), "+": (prec: 2, rAssoc: false), "-": (prec: 2, rAssoc: false), ] func rpn(tokens: [String]) -> [String] { var rpn: [String] = [] var stack: [String] = []
479Parsing/RPN calculator algorithm
17swift
8r60v
import java.util.ArrayList; ...
481Pascal's triangle
9java
8rz06
null
481Pascal's triangle
10javascript
fb9dg
use strict; use warnings; use feature 'say'; sub pangram1 { my($str,@set) = @_; use List::MoreUtils 'all'; all { $str =~ /$_/i } @set; } sub pangram2 { my($str,@set) = @_; '' eq (join '',@set) =~ s/[$str]//gir; } my @alpha = 'a' .. 'z'; for ( 'Cozy Lummox Gives Smart Squid Who Asks For Job Pen.', 'Crabby Lummox Gives Smart Squid Who Asks For Job Pen.' ) { say pangram1($_,@alpha) ? 'Yes' : 'No'; say pangram2($_,@alpha) ? 'Yes' : 'No'; }
482Pangram checker
2perl
gfb4e
function isPangram($text) { foreach (str_split($text) as $c) { if ($c >= 'a' && $c <= 'z') $bitset |= (1 << (ord($c) - ord('a'))); else if ($c >= 'A' && $c <= 'Z') $bitset |= (1 << (ord($c) - ord('A'))); } return $bitset == 0x3ffffff; } $test = array( , , , , ); foreach ($test as $str) echo , isPangram($str)? 'T' : 'F', '</br>';
482Pangram checker
12php
nh6ig
fun pas(rows: Int) { for (i in 0..rows - 1) { for (j in 0..i) print(ncr(i, j).toString() + " ") println() } } fun ncr(n: Int, r: Int) = fact(n) / (fact(r) * fact(n - r)) fun fact(n: Int): Long { var ans = 1.toLong() for (i in 2..n) ans *= i return ans } fun main(args: Array<String>) = pas(args[0].toInt())
481Pascal's triangle
11kotlin
wviek
import string, sys if sys.version_info[0] < 3: input = raw_input def ispangram(sentence, alphabet=string.ascii_lowercase): alphaset = set(alphabet) return alphaset <= set(sentence.lower()) print ( ispangram(input('Sentence: ')) )
482Pangram checker
3python
rtpgq
checkPangram <- function(sentence){ my.letters <- tolower(unlist(strsplit(sentence, ""))) is.pangram <- all(letters%in% my.letters) if (is.pangram){ cat("\"", sentence, "\" is a pangram! \n", sep="") } else { cat("\"", sentence, "\" is not a pangram! \n", sep="") } }
482Pangram checker
13r
uijvx
import Data.Ratio import Data.List (find) import GHC.TypeLits import Padic pSqrt :: KnownNat p => Rational -> Padic p pSqrt r = res where res = maybe Null mkUnit series (a, b) = (numerator r, denominator r) series = case modulo res of 2 | eqMod 4 a 3 -> Nothing | not (eqMod 8 a 1) -> Nothing | otherwise -> Just $ 1: 0: go 8 1 where go pk x = let q = ((b*x*x - a) `div` pk) `mod` 2 in q: go (2*pk) (x + q * (pk `div` 2)) p -> do y <- find (\x -> eqMod p (b*x*x) a) [1..p-1] df <- recipMod p (2*b*y) let go pk x = let f = (b*x*x - a) `div` pk d = (f * (p - df)) `mod` p in x `div` (pk `div` p): go (p*pk) (x + d*pk) Just $ go p y eqMod :: Integral a => a -> a -> a -> Bool eqMod p a b = a `mod` p == b `mod` p
484P-Adic square roots
8haskell
vog2k
function nextrow(t) local ret = {} t[0], t[#t+1] = 0, 0 for i = 1, #t do ret[i] = t[i-1] + t[i] end return ret end function triangle(n) t = {1} for i = 1, n do print(unpack(t)) t = nextrow(t) end end
481Pascal's triangle
1lua
xunwz
def pangram?(sentence) s = sentence.downcase ('a'..'z').all? {|char| s.include? (char) } end p pangram?('this is a sentence') p pangram?('The quick brown fox jumps over the lazy dog.')
482Pangram checker
14ruby
j3a7x
#![feature(test)] extern crate test; use std::collections::HashSet; pub fn is_pangram_via_bitmask(s: &str) -> bool {
482Pangram checker
15rust
h6ej2
def is_pangram(sentence: String) = sentence.toLowerCase.filter(c => c >= 'a' && c <= 'z').toSet.size == 26
482Pangram checker
16scala
p9qbj
import Foundation let str = "the quick brown fox jumps over the lazy dog" func isPangram(str:String) -> Bool { let stringArray = Array(str.lowercaseString) for char in "abcdefghijklmnopqrstuvwxyz" { if (find(stringArray, char) == nil) { return false } } return true } isPangram(str)
482Pangram checker
17swift
7z1rq
package main import "fmt"
485P-Adic numbers, basic
0go
q58xz
void padovanN(int n, size_t t, int *p) { int i, j; if (n < 2 || t < 3) { for (i = 0; i < t; ++i) p[i] = 1; return; } padovanN(n-1, t, p); for (i = n + 1; i < t; ++i) { p[i] = 0; for (j = i - 2; j >= i - n - 1; --j) p[i] += p[j]; } } int main() { int n, i; const size_t t = 15; int p[t]; printf(, t); for (n = 2; n <= 8; ++n) { for (i = 0; i < t; ++i) p[i] = 0; padovanN(n, t, p); printf(, n); for (i = 0; i < t; ++i) printf(, p[i]); printf(); } return 0; }
486Padovan n-step number sequences
5c
nhfi6
module Padic where import Data.Ratio import Data.List (genericLength) import GHC.TypeLits data Padic (n :: Nat) = Null | Padic { unit :: [Int], order :: Int } modulo :: (KnownNat p, Integral i) => Padic p -> i modulo = fromIntegral . natVal pZero :: KnownNat p => Padic p pZero = Padic (repeat 0) 0 mkPadic :: (KnownNat p, Integral i) => [i] -> Int -> Padic p mkPadic u k = go 0 (fromIntegral <$> u) where go 17 _ = pZero go i (0:u) = go (i+1) u go i u = Padic u (k-i) mkUnit :: (KnownNat p, Integral i) => [i] -> Padic p mkUnit u = mkPadic u 0 isZero :: KnownNat p => Padic p -> Bool isZero (Padic u _) = all (== 0) (take 17 u) isZero _ = False pNorm :: KnownNat p => Padic p -> Ratio Int pNorm Null = undefined pNorm p = fromIntegral (modulo p) ^^ (- order p) isInteger :: KnownNat p => Padic p -> Bool isInteger Null = False isInteger (Padic s k) = case splitAt k s of ([],i) -> length (takeWhile (==0) $ reverse (take 20 i)) > 3 _ -> False instance KnownNat p => Show (Padic p) where show Null = "Null" show x@(Padic u k) = show (modulo x) ++ "-adic: " ++ (case si of {[] -> "0"; _ -> si}) ++ "." ++ (case f of {[] -> "0"; _ -> sf}) where (f,i) = case compare k 0 of LT -> ([], replicate (-k) 0 ++ u) EQ -> ([], u) GT -> splitAt k (u ++ repeat 0) sf = foldMap showD $ reverse $ take 17 f si = foldMap showD $ dropWhile (== 0) $ reverse $ take 17 i el s = if length s > 16 then "" else "" showD n = [(['0'..'9']++['a'..'z']) !! n] instance KnownNat p => Eq (Padic p) where a == b = isZero (a - b) instance KnownNat p => Ord (Padic p) where compare = error "Ordering is undefined fo p-adics." instance KnownNat p => Num (Padic p) where fromInteger 0 = pZero fromInteger n = pAdic (fromInteger n) x@(Padic a ka) + Padic b kb = mkPadic s k where k = ka `max` kb s = addMod (modulo x) (replicate (k-ka) 0 ++ a) (replicate (k-kb) 0 ++ b) _ + _ = Null x@(Padic a ka) * Padic b kb = mkPadic (mulMod (modulo x) a b) (ka + kb) _ * _ = Null negate x@(Padic u k) = case map (\y -> modulo x - 1 - y) u of n:ns -> Padic ((n+1):ns) k [] -> pZero negate _ = Null abs p = pAdic (pNorm p) signum = undefined instance KnownNat p => Fractional (Padic p) where fromRational = pAdic recip Null = Null recip x@(Padic (u:us) k) | isZero x = Null | gcd p u /= 1 = Null | otherwise = mkPadic res (-k) where p = modulo x res = longDivMod p (1:repeat 0) (u:us) pAdic :: (Show i, Integral i, KnownNat p) => Ratio i -> Padic p pAdic 0 = pZero pAdic x = res where p = modulo res (k, q) = getUnit p x (n, d) = (numerator q, denominator q) res = maybe Null process $ recipMod p d process r = mkPadic (series n) k where series n | n == 0 = repeat 0 | n `mod` p == 0 = 0: series (n `div` p) | otherwise = let m = (n * r) `mod` p in m: series ((n - m * d) `div` p) instance KnownNat p => Real (Padic p) where toRational Null = error "no rational representation!" toRational x@(Padic s k) = res where p = modulo x res = case break isInteger $ take 10000 $ iterate (x +) x of (_,[]) -> - toRational (- x) (d, i:_) -> (fromBase p (unit i) * (p^(- order i))) % (genericLength d + 1) fromBase p = foldr (\x r -> r*p + x) 0 . take 20 . map fromIntegral getUnit :: Integral i => i -> Ratio i -> (Int, Ratio i) getUnit p x = (genericLength k1 - genericLength k2, c) where (k1,b:_) = span (\n -> denominator n `mod` p == 0) $ iterate (* fromIntegral p) x (k2,c:_) = span (\n -> numerator n `mod` p == 0) $ iterate (/ fromIntegral p) b recipMod :: Integral i => i -> i -> Maybe i recipMod p 1 = Just 1 recipMod p a | gcd p a == 1 = Just $ go 0 1 p a | otherwise = Nothing where go t _ _ 0 = t `mod` p go t nt r nr = let q = r `div` nr in go nt (t - q*nt) nr (r - q*nr) addMod p = go 0 where go 0 [] ys = ys go 0 xs [] = xs go s [] ys = go 0 [s] ys go s xs [] = go 0 xs [s] go s (x:xs) (y:ys) = let (q, r) = (x + y + s) `divMod` p in r: go q xs ys subMod p a (b:bs) = addMod p a $ (p-b): ((p - 1 -) <$> bs) mulMod p as [b] = mulMod p [b] as mulMod p as bs = case as of [0] -> repeat 0 [1] -> bs [a] -> go 0 bs where go s [] = [s] go s (b:bs) = let (q, r) = (a * b + s) `divMod` p in r: go q bs as -> go bs where go [] = [] go (b:bs) = let c:cs = mulMod p [b] as in c: addMod p (go bs) cs longDivMod p a (b:bs) = case recipMod p b of Nothing -> error $ show b ++ " is not invertible modulo " ++ show p Just r -> go a where go [] = [] go (0:xs) = 0: go xs go (x:xs) = let m = (x*r) `mod` p _:zs = subMod p (x:xs) (mulMod p [m] (b:bs)) in m: go zs
485P-Adic numbers, basic
8haskell
mxlyf
package main import "fmt" func padovanN(n, t int) []int { if n < 2 || t < 3 { ones := make([]int, t) for i := 0; i < t; i++ { ones[i] = 1 } return ones } p := padovanN(n-1, t) for i := n + 1; i < t; i++ { p[i] = 0 for j := i - 2; j >= i-n-1; j-- { p[i] += p[j] } } return p } func main() { t := 15 fmt.Println("First", t, "terms of the Padovan n-step number sequences:") for n := 2; n <= 8; n++ { fmt.Printf("%d:%3d\n", n, padovanN(n, t)) } }
486Padovan n-step number sequences
0go
rtjgm
import Data.Bifunctor (second) import Data.List (transpose, uncons, unfoldr) padovans :: Int -> [Int] padovans n | 0 > n = [] | otherwise = unfoldr (recurrence n) $ take (succ n) xs where xs | 3 > n = repeat 1 | otherwise = padovans $ pred n recurrence :: Int -> [Int] -> Maybe (Int, [Int]) recurrence n = ( fmap . second . flip (<>) . pure . sum . take n ) <*> uncons main :: IO () main = putStrLn $ "Padovan N-step series:\n\n" <> spacedTable justifyRight ( fmap ( \n -> [show n <> " -> "] <> fmap show (take 15 $ padovans n) ) [2 .. 8] ) spacedTable :: (Int -> Char -> String -> String) -> [[String]] -> String spacedTable aligned rows = unlines $ fmap (unwords . zipWith (`aligned` ' ') columnWidths) rows where columnWidths = fmap (maximum . fmap length) (transpose rows) justifyRight :: Int -> a -> [a] -> [a] justifyRight n c = drop . length <*> (replicate n c <>)
486Padovan n-step number sequences
8haskell
0gos7
(() => { "use strict";
486Padovan n-step number sequences
10javascript
s48qz
int next_perm(int size, int * nums) { int *l, *k, tmp; for (k = nums + size - 2; k >= nums && k[0] >= k[1]; k--) {}; if (k < nums) return 0; for (l = nums + size - 1; *l <= *k; l--) {}; tmp = *k; *k = *l; *l = tmp; for (l = nums + size - 1, k++; k < l; k++, l--) { tmp = *k; *k = *l; *l = tmp; } return 1; } void make_part(int n, int * sizes) { int x[1024], i, j, *ptr, len = 0; for (ptr = x, i = 0; i < n; i++) for (j = 0, len += sizes[i]; j < sizes[i]; j++, *(ptr++) = i); do { for (i = 0; i < n; i++) { printf(); for (j = 0; j < len; j++) if (x[j] == i) printf(, j); printf(); } printf(); } while (next_perm(len, x)); } int main() { int s1[] = {2, 0, 2}; int s2[] = {1, 2, 3, 4}; printf(); make_part(3, s1); printf(); make_part(4, s2); return 1; }
487Ordered partitions
5c
j3h70
package pal func IsPal(s string) bool { mid := len(s) / 2 last := len(s) - 1 for i := 0; i < mid; i++ { if s[i] != s[last-i] { return false } } return true }
483Palindrome detection
0go
0gdsk
use strict; use warnings; use feature <state say>; use List::Util 'sum'; use List::Lazy 'lazy_list'; say 'Padovan N-step sequences; first 25 terms:'; for our $N (2..8) { my $pad_n = lazy_list { state $n = 2; state @pn = (1, 1, 1); push @pn, sum @pn[ grep { $_ >= 0 } $n-$N .. $n++ - 1 ]; $pn[-4] }; print "N = $N |"; print ' ' . $pad_n->next() for 1..25; print "\n" }
486Padovan n-step number sequences
2perl
z16tb
def isPalindrome = { String s -> s == s?.reverse() }
483Palindrome detection
7groovy
e20al
is_palindrome x = x == reverse x
483Palindrome detection
8haskell
cs594
def pad_like(max_n=8, t=15): start = [[], [1, 1, 1]] for n in range(2, max_n+1): this = start[n-1][:n+1] while len(this) < t: this.append(sum(this[i] for i in range(-2, -n - 2, -1))) start.append(this) return start[2:] def pr(p): print(''' :::: {| style= border= cellpadding= cellspacing= |+ Padovan <math>n</math>-step sequences |- style= ! <math>n</math>!! Values |- '''.strip()) for n, seq in enumerate(p, 2): print(f) print('|}') if __name__ == '__main__': p = pad_like() pr(p)
486Padovan n-step number sequences
3python
3ayzc
fn padovan(n: u64, x: u64) -> u64 { if n < 2 { return 0; } match n { 2 if x <= n + 1 => 1, 2 => padovan(n, x - 2) + padovan(n, x - 3), _ if x <= n + 1 => padovan(n - 1, x), _ => ((x - n - 1)..(x - 1)).fold(0, |acc, value| acc + padovan(n, value)), } } fn main() { (2..=8).for_each(|n| { print!("\nN={}: ", n); (1..=15).for_each(|x| print!("{},", padovan(n, x))) }); }
486Padovan n-step number sequences
15rust
mxcya
sub pascal { my $rows = shift; my @next = (1); for my $n (1 .. $rows) { print "@next\n"; @next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1); } }
481Pascal's triangle
2perl
l0rc5
bool is_palindrome(const char* str) { size_t n = strlen(str); for (size_t i = 0; i + 1 < n; ++i, --n) { if (str[i] != str[n - 1]) return false; } return true; } int main() { time_t timestamp = time(0); const int seconds_per_day = 24*60*60; int count = 15; char str[32]; printf(, count); for (; count > 0; timestamp += seconds_per_day) { struct tm* ptr = gmtime(&timestamp); strftime(str, sizeof(str), , ptr); if (is_palindrome(str)) { strftime(str, sizeof(str), , ptr); printf(, str); --count; } } return 0; }
488Palindrome dates
5c
ala11
<?php function tre($n) { $ck=1; $kn=$n+1; if($kn%2==0) { $kn=$kn/2; $i=0; } else { $kn+=1; $kn=$kn/2; $i= 1; } for ($k = 1; $k <= $kn-1; $k++) { $ck = $ck/$k*($n-$k+1); $arr[] = $ck; echo . $ck ; } if ($kn>1) { echo $arr[i]; $arr=array_reverse($arr); for ($i; $i<= $kn-1; $i++) { echo . $arr[$i] ; } } } while ($n<=20) { ++$n; echo tre($n); echo ; } ?>
481Pascal's triangle
12php
q5dx3
public static boolean pali(String testMe){ StringBuilder sb = new StringBuilder(testMe); return testMe.equals(sb.reverse().toString()); }
483Palindrome detection
9java
z19tq
package main import ( "fmt" "os" "strconv" ) func gen_part(n, res []int, pos int) { if pos == len(res) { x := make([][]int, len(n)) for i, c := range res { x[c] = append(x[c], i+1) } fmt.Println(x) return } for i := range n { if n[i] == 0 { continue } n[i], res[pos] = n[i]-1, i gen_part(n, res, pos+1) n[i]++ } } func ordered_part(n_parts []int) { fmt.Println("Ordered", n_parts) sum := 0 for _, c := range n_parts { sum += c } gen_part(n_parts, make([]int, sum), 0) } func main() { if len(os.Args) < 2 { ordered_part([]int{2, 0, 2}) return } n := make([]int, len(os.Args)-1) var err error for i, a := range os.Args[1:] { n[i], err = strconv.Atoi(a) if err != nil { fmt.Println(err) return } if n[i] < 0 { fmt.Println("negative partition size not meaningful") return } } ordered_part(n) }
487Ordered partitions
0go
fbtd0
int pRec(int n) { static int *memo = NULL; static size_t curSize = 0; if (curSize <= (size_t) n) { size_t lastSize = curSize; while (curSize <= (size_t) n) curSize += 1024 * sizeof(int); memo = realloc(memo, curSize * sizeof(int)); memset(memo + lastSize, 0, (curSize - lastSize) * sizeof(int)); } if (memo[n] == 0) { if (n<=2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); } return memo[n]; } int pFloor(int n) { long double p = 1.324717957244746025960908854; long double s = 1.0453567932525329623; return powl(p, n-1)/s + 0.5; } void nextLSystem(const char *prev, char *buf) { while (*prev) { switch (*prev++) { case 'A': *buf++ = 'B'; break; case 'B': *buf++ = 'C'; break; case 'C': *buf++ = 'A'; *buf++ = 'B'; break; } } *buf = '\0'; } int main() { char buf1[BUFSZ], buf2[BUFSZ]; int i; printf(); for (i=0; i<20; i++) printf(, pRec(i)); printf(); printf(); for (i=0; i<64; i++) { if (pRec(i) != pFloor(i)) { printf(, i, pRec(i), pFloor(i)); break; } } if (i == 64) { printf(); } printf(); for (strcpy(buf1, ), i=0; i<10; i++) { printf(, buf1); strcpy(buf2, buf1); nextLSystem(buf2, buf1); } printf(); for (strcpy(buf1, ), i=0; i<32; i++) { if ((int)strlen(buf1) != pFloor(i)) { printf(, i, (int)strlen(buf1), pFloor(i)); break; } strcpy(buf2, buf1); nextLSystem(buf2, buf1); } if (i == 32) { printf(); } return 0; }
489Padovan sequence
5c
i78o2
function isPalindrome(str) { return str === str.split("").reverse().join(""); } console.log(isPalindrome("ingirumimusnocteetconsumimurigni"));
483Palindrome detection
10javascript
9quml
(defn valid-date? [[y m d]] (and (<= 1 m 12) (<= 1 d 31))) (defn date-str [[y m d]] (format "%4d-%02d-%02d" y m d)) (defn yr->date [y] (let [[_ m d] (re-find #"(..)(..)" (apply str (reverse (str y))))] [y (Long. m) (Long. d)])) (defn palindrome-dates [start-yr n] (->> (iterate inc start-yr) (map yr->date) (filter valid-date?) (map date-str) (take n)))
488Palindrome dates
6clojure
s4sqr
def partitions = { int... sizes -> int n = (sizes as List).sum() def perms = n == 0 ? [[]]: (1..n).permutations() Set parts = perms.collect { p -> sizes.collect { s -> (0..<s).collect { p.pop() } as Set } } parts.sort{ a, b -> if (!a) return 0 def comp = [a,b].transpose().find { aa, bb -> aa != bb } if (!comp) return 0 def recomp = comp.collect{ it as List }.transpose().find { aa, bb -> aa != bb } if (!recomp) return 0 return recomp[0] <=> recomp[1] } }
487Ordered partitions
7groovy
8ro0b
import Data.List ((\\)) comb :: Int -> [a] -> [[a]] comb 0 _ = [[]] comb _ [] = [] comb k (x:xs) = map (x:) (comb (k-1) xs) ++ comb k xs partitions :: [Int] -> [[[Int]]] partitions xs = p [1..sum xs] xs where p _ [] = [[]] p xs (k:ks) = [ cs:rs | cs <- comb k xs, rs <- p (xs \\ cs) ks ] main = print $ partitions [2,0,2]
487Ordered partitions
8haskell
4dg5s
(def padovan (map first (iterate (fn [[a b c]] [b c (+ a b)]) [1 1 1]))) (def pad-floor (let [p 1.324717957244746025960908854 s 1.0453567932525329623] (map (fn [n] (int (Math/floor (+ (/ (Math/pow p (dec n)) s) 0.5)))) (range)))) (def pad-l (iterate (fn f [[c & s]] (case c \A (str "B" (f s)) \B (str "C" (f s)) \C (str "AB" (f s)) (str ""))) "A")) (defn comp-seq [n seqa seqb] (= (take n seqa) (take n seqb))) (defn comp-all [n] (= (map count (vec (take n pad-l))) (take n padovan) (take n pad-floor))) (defn padovan-print [& args] ((print "The first 20 items with recursion relation are: ") (println (take 20 padovan)) (println) (println (str "The recurrence and floor based algorithms " (if (comp-seq 64 padovan pad-floor) "match" "not match") " to n=64")) (println) (println "The first 10 L-system strings are:") (println (take 10 pad-l)) (println) (println (str "The L-system, recurrence and floor based algorithms " (if (comp-all 32) "match" "not match") " to n=32"))))
489Padovan sequence
6clojure
zpftj
(function () { 'use strict';
487Ordered partitions
10javascript
5n4ur
package main import ( "fmt" "time" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { const ( layout = "20060102" layout2 = "2006-01-02" ) fmt.Println("The next 15 palindromic dates in yyyymmdd format after 20200202 are:") date := time.Date(2020, 2, 2, 0, 0, 0, 0, time.UTC) count := 0 for count < 15 { date = date.AddDate(0, 0, 1) s := date.Format(layout) r := reverse(s) if r == s { fmt.Println(date.Format(layout2)) count++ } } }
488Palindrome dates
0go
mxmyi
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(big.Rat), new(big.Rat), new(big.Rat) p, _ = p.SetString("1.324717957244746025960908854") s, _ = s.SetString("1.0453567932525329623") f := make([]int, n) pow := new(big.Rat).SetInt64(1) u = u.SetFrac64(1, 2) t.Quo(pow, p) t.Quo(t, s) t.Add(t, u) v, _ := t.Float64() f[0] = int(math.Floor(v)) for i := 1; i < n; i++ { t.Quo(pow, s) t.Add(t, u) v, _ = t.Float64() f[i] = int(math.Floor(v)) pow.Mul(pow, p) } return f } type LSystem struct { rules map[string]string init, current string } func step(lsys *LSystem) string { var sb strings.Builder if lsys.current == "" { lsys.current = lsys.init } else { for _, c := range lsys.current { sb.WriteString(lsys.rules[string(c)]) } lsys.current = sb.String() } return lsys.current } func padovanLSys(n int) []string { rules := map[string]string{"A": "B", "B": "C", "C": "AB"} lsys := &LSystem{rules, "A", ""} p := make([]string, n) for i := 0; i < n; i++ { p[i] = step(lsys) } return p }
489Padovan sequence
0go
gd54n
import Data.Time.Calendar (Day, fromGregorianValid) import Data.List.Split (chunksOf) import Data.List (unfoldr) import Data.Tuple (swap) import Data.Bool (bool) import Data.Maybe (mapMaybe) palinDates :: [Day] palinDates = mapMaybe palinDay [2021 .. 9999] palinDay :: Integer -> Maybe Day palinDay y = fromGregorianValid y m d where [m, d] = unDigits <$> chunksOf 2 (reversedDecimalDigits (fromInteger y)) reversedDecimalDigits :: Int -> [Int] reversedDecimalDigits = unfoldr ((flip bool Nothing . Just . swap . flip quotRem 10) <*> (0 ==)) unDigits :: [Int] -> Int unDigits = foldl ((+) . (10 *)) 0 main :: IO () main = do let n = length palinDates putStrLn $ "Count of palindromic dates [2021..9999]: " ++ show n putStrLn "\nFirst 15:" mapM_ print $ take 15 palinDates putStrLn "\nLast 15:" mapM_ print $ take 15 (drop (n - 15) palinDates)
488Palindrome dates
8haskell
kykh0
null
487Ordered partitions
11kotlin
3a6z5
pRec = map (\(a,_,_) -> a) $ iterate (\(a,b,c) -> (b,c,a+b)) (1,1,1) pSelfRef = 1: 1: 1: zipWith (+) pSelfRef (tail pSelfRef) pFloor = map f [0..] where f n = floor $ p**fromInteger (pred n) / s + 0.5 p = 1.324717957244746025960908854 s = 1.0453567932525329623 lSystem = iterate f "A" where f [] = [] f ('A':s) = 'B':f s f ('B':s) = 'C':f s f ('C':s) = 'A':'B':f s checkN n as bs = take n as == take n bs main = do putStr "P_0 .. P_19: " putStrLn $ unwords $ map show $ take 20 pRec putStr "The floor- and recurrence-based functions " putStr $ if checkN 64 pRec pFloor then "match" else "do not match" putStr " from P_0 to P_63.\n" putStr "The self-referential- and recurrence-based functions " putStr $ if checkN 64 pRec pSelfRef then "match" else "do not match" putStr " from P_0 to P_63.\n\n" putStr "The first 10 L-system strings are:\n" putStrLn $ unwords $ take 10 lSystem putStr "\nThe floor- and L-system-based functions " putStr $ if checkN 32 pFloor (map length lSystem) then "match" else "do not match" putStr " from P_0 to P_31.\n"
489Padovan sequence
8haskell
s5xqk
null
483Palindrome detection
11kotlin
ijzo4
import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class PalindromeDates { public static void main(String[] args) { LocalDate date = LocalDate.of(2020, 2, 3); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); DateTimeFormatter formatterDash = DateTimeFormatter.ofPattern("yyyy-MM-dd"); System.out.printf("First 15 palindrome dates after 2020-02-02 are:%n"); for ( int count = 0 ; count < 15 ; date = date.plusDays(1) ) { String dateFormatted = date.format(formatter); if ( dateFormatted.compareTo(new StringBuilder(dateFormatted).reverse().toString()) == 0 ) { count++; System.out.printf("date =%s%n", date.format(formatterDash)); } } } }
488Palindrome dates
9java
4d458
null
487Ordered partitions
1lua
6ey39
def pascal(n): row = [1] k = [0] for x in range(max(n,0)): print row row=[l+r for l,r in zip(row+k,k+row)] return n>=1
481Pascal's triangle
3python
287lz