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(... | 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.concurren... | 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
... | 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
matri... | 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("... | 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,... | 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(pre... | 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): Uni... | 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.j... | 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) {
... | 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... | 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(o... | 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)
... | 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,
}
... | 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][... | 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 == "+"... | 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
ec... | 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
... | 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):
... | 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] <... | 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.Pr... | 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))
(... | 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... | 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]);
}
... | 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(... | 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!(... | 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: Stac... | 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 P... | 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(
,
,
... | 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 mai... | 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) -> Not... | 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
}
isPan... | 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;
... | 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 (repe... | 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; ... | 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])
rec... | 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--) {
... | 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 ];
... | 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('''
:::: {| styl... | 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() {... | 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... | 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... | 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_par... | 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 - ... | 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)
... | 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... | 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 ]
m... | 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
... | 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... | 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(bi... | 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 = fromGregorianVa... | 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"
... | 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 =... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.