code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
while (true) { $a = rand(0,19); echo ; if ($a == 10) break; $b = rand(0,19); echo ; }
640Loops/Break
12php
wm5ep
let you = "You" let str1 = "\(you) can insert variables into strings." let str2 = "Swift also supports unicode in strings " let str3 = "Swift also supports control characters \n\tLike this" let str4 = "'"
643Literals/String
17swift
dghnh
print 2**64*2**64
646Long multiplication
3python
mp1yh
let hex = 0x2F
645Literals/Integer
17swift
slvqt
rlcs(_ s1: String, _ s2: String) -> String { if s1.count == 0 || s2.count == 0 { return "" } else if s1[s1.index(s1.endIndex, offsetBy: -1)] == s2[s2.index(s2.endIndex, offsetBy: -1)] { return rlcs(String(s1[s1.startIndex..<s1.index(s1.endIndex, offsetBy: -1)]), String(s2[s2.startIndex..<s2.index(s2.endIndex, offsetBy: -1)])) + String(s1[s1.index(s1.endIndex, offsetBy: -1)]) } else { let str1 = rlcs(s1, String(s2[s2.startIndex..<s2.index(s2.endIndex, offsetBy: -1)])) let str2 = rlcs(String(s1[s1.startIndex..<s1.index(s1.endIndex, offsetBy: -1)]), s2) return str1.count > str2.count? str1: str2 } }
637Longest common subsequence
17swift
kf2hx
library(gmp) a <- as.bigz("18446744073709551616") mul.bigz(a,a)
646Long multiplication
13r
zjhth
from random import randrange while True: a = randrange(20) print(a) if a == 10: break b = randrange(20) print(b)
640Loops/Break
3python
ca89q
a1, a2, a3 = {'a' , 'b' , 'c' } , { 'A' , 'B' , 'C' } , { 1 , 2 , 3 } for i = 1, 3 do print(a1[i]..a2[i]..a3[i]) end
644Loop over multiple arrays simultaneously
1lua
jnt71
sample0to19 <- function() sample(0L:19L, 1,replace=TRUE) repeat { result1 <- sample0to19() if (result1 == 10L) { print(result1) break } result2 <- sample0to19() cat(result1, result2, "\n") }
640Loops/Break
13r
6kx3e
sub show_bool { return shift() ? 'true' : 'false', "\n"; } sub test_logic { my ($a, $b) = @_; print "a and b is ", show_bool $a && $b; print "a or b is ", show_bool $a || $b; print "not a is ", show_bool !$a; print "a xor b is ", show_bool($a xor $b); }
647Logical operations
2perl
4005d
def longmult(x,y) result = [0] j = 0 y.digits.each do |m| c = 0 i = j x.digits.each do |d| v = result[i] result << 0 if v.zero? c, v = (v + c + d*m).divmod(10) result[i] = v i += 1 end result[i] += c j += 1 end result.reverse.inject(0) {|sum, n| 10*sum + n} end n=2**64 printf , n, n, n*n printf , n, n, longmult(n,n)
646Long multiplication
14ruby
cae9k
function print_logic($a, $b) { echo , $a && $b? 'True' : 'False', ; echo , $a || $b? 'True' : 'False', ; echo , ! $a? 'True' : 'False', ; }
647Logical operations
12php
i55ov
sub lookandsay { my $str = shift; $str =~ s/((.)\2*)/length($1) . $2/ge; return $str; } my $num = "1"; foreach (1..10) { print "$num\n"; $num = lookandsay($num); }
642Look-and-say sequence
2perl
dgknw
def addNums(x: String, y: String) = { val padSize = x.length max y.length val paddedX = "0" * (padSize - x.length) + x val paddedY = "0" * (padSize - y.length) + y val (sum, carry) = (paddedX zip paddedY).foldRight(("", 0)) { case ((dx, dy), (acc, carry)) => val sum = dx.asDigit + dy.asDigit + carry ((sum % 10).toString + acc, sum / 10) } if (carry != 0) carry.toString + sum else sum } def multByDigit(num: String, digit: Int) = { val (mult, carry) = num.foldRight(("", 0)) { case (d, (acc, carry)) => val mult = d.asDigit * digit + carry ((mult % 10).toString + acc, mult / 10) } if (carry != 0) carry.toString + mult else mult } def mult(x: String, y: String) = y.foldLeft("")((acc, digit) => addNums(acc + "0", multByDigit(x, digit.asDigit)))
646Long multiplication
16scala
uqsv8
loop do a = rand(20) print a if a == 10 puts break end b = rand(20) puts end
640Loops/Break
14ruby
2wilw
null
640Loops/Break
15rust
vxn2t
<?php function lookAndSay($str) { return preg_replace_callback(' return strlen($matches[0]).$matches[1]; }, $str); } $num = ; foreach(range(1,10) as $i) { echo $num.; $num = lookAndSay($num); } ?>
642Look-and-say sequence
12php
jn37z
scala> import util.control.Breaks.{breakable, break} import util.control.Breaks.{breakable, break} scala> import util.Random import util.Random scala> breakable { | while(true) { | val a = Random.nextInt(20) | println(a) | if(a == 10) | break | val b = Random.nextInt(20) | println(b) | } | } 5 4 10
640Loops/Break
16scala
40t50
def logic(a, b): print('a and b:', a and b) print('a or b:', a or b) print('not a:', not a)
647Logical operations
3python
g884h
logic <- function(a, b) { print(a && b) print(a || b) print(! a) } logic(TRUE, TRUE) logic(TRUE, FALSE) logic(FALSE, FALSE)
647Logical operations
13r
vxx27
while true { let a = Int(arc4random())% (20) print("a: \(a)",terminator: " ") if (a == 10) { break } let b = Int(arc4random())% (20) print("b: \(b)") }
640Loops/Break
17swift
leoc2
def lookandsay(number): result = repeat = number[0] number = number[1:]+ times = 1 for actual in number: if actual != repeat: result += str(times)+repeat times = 1 repeat = actual else: times += 1 return result num = for i in range(10): print num num = lookandsay(num)
642Look-and-say sequence
3python
frbde
for(my $x = 1; $x <= 5; $x++) { for(my $y = 1; $y <= $x; $y++) { print "*"; } print "\n"; }
630Loops/For
2perl
zjdtb
def logic(a, b) print 'a and b: ', a && b, print 'a or b: ' , a || b, print 'not a: ' ,!a , print 'a xor b: ' , a ^ b, end
647Logical operations
14ruby
7iiri
fn boolean_ops(a: bool, b: bool) { println!("{} and {} -> {}", a, b, a && b); println!("{} or {} -> {}", a, b, a || b); println!("{} xor {} -> {}", a, b, a ^ b); println!("not {} -> {}\n", a,!a); } fn main() { boolean_ops(true, true); boolean_ops(true, false); boolean_ops(false, true); boolean_ops(false, false) }
647Logical operations
15rust
jnn72
def logical(a: Boolean, b: Boolean): Unit = { println("and: " + (a && b)) println("or: " + (a || b)) println("not: " + !a) } logical(true, false)
647Logical operations
16scala
bttk6
look.and.say <- function(x, return.an.int=FALSE) { xstr <- unlist(strsplit(as.character(x), "")) rlex <- rle(xstr) odds <- as.character(rlex$lengths) evens <- rlex$values newstr <- as.vector(rbind(odds, evens)) newstr <- paste(newstr, collapse="") if(return.an.int) as.integer(newstr) else newstr }
642Look-and-say sequence
13r
ou784
for ($i = 1; $i <= 5; $i++) { for ($j = 1; $j <= $i; $j++) { echo '*'; } echo ; }
630Loops/For
12php
btjk9
sub zip (&@) { my $code = shift; my $min; $min = $min && $ for my $i(0..$min){ $code->(map $_->[$i] ,@_) } } my @a1 = qw( a b c ); my @a2 = qw( A B C ); my @a3 = qw( 1 2 3 ); zip { print @_,"\n" }\(@a1, @a2, @a3);
644Loop over multiple arrays simultaneously
2perl
frhd7
class String def look_and_say gsub(/(.)\1*/){|s| s.size.to_s + s[0]} end end ss = '1' 12.times {puts ss; ss = ss.look_and_say}
642Look-and-say sequence
14ruby
zj1tw
func logic(a: Bool, b: Bool) { println("a AND b: \(a && b)"); println("a OR b: \(a || b)"); println("NOT a: \(!a)"); }
647Logical operations
17swift
roogg
fn next_sequence(in_seq: &[i8]) -> Vec<i8> { assert!(!in_seq.is_empty()); let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { result.push(current_runlength); result.push(current_number); current_runlength = 1; current_number = *i; } } result.push(current_runlength); result.push(current_number); result } fn main() { let mut seq = vec![1]; for i in 0..10 { println!("Sequence {}: {:?}", i, seq); seq = next_sequence(&seq); } }
642Look-and-say sequence
15rust
3haz8
$a = array('a', 'b', 'c'); $b = array('A', 'B', 'C'); $c = array('1', '2', '3'); saves PHP from casting them later if ((sizeOf($a) !== sizeOf($b)) || (sizeOf($b) !== sizeOf($c))){ throw new Exception('All three arrays must be the same length'); } foreach ($a as $key => $value){ echo ; }
644Loop over multiple arrays simultaneously
12php
hdzjf
import scala.annotation.tailrec object LookAndSay extends App { loop(10, "1") @tailrec private def loop(n: Int, num: String): Unit = { println(num) if (n <= 0) () else loop(n - 1, lookandsay(num)) } private def lookandsay(number: String): String = { val result = new StringBuilder @tailrec def loop(numberString: String, repeat: Char, times: Int): String = if (numberString.isEmpty) result.toString() else if (numberString.head != repeat) { result.append(times).append(repeat) loop(numberString.tail, numberString.head, 1) } else loop(numberString.tail, numberString.head, times + 1) loop(number.tail + " ", number.head, 1) } }
642Look-and-say sequence
16scala
mpxyc
typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf(, a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf(, p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven(, ); return 0; }
648Levenshtein distance/Alignment
5c
pztby
import sys for i in xrange(5): for j in xrange(i+1): sys.stdout.write() print
630Loops/For
3python
3hfzc
DROP VIEW delta; CREATE VIEW delta AS SELECT sequence1.v AS x, (sequence1.v<>sequence2.v)*sequence1.c AS v, sequence1.c AS c FROM SEQUENCE AS sequence1, SEQUENCE AS sequence2 WHERE sequence1.c = sequence2.c+1; DROP VIEW rle0; CREATE VIEW rle0 AS SELECT delta2.x AS x, SUM(delta2.v) AS v, delta2.c AS c FROM delta AS delta1, delta AS delta2 WHERE delta1.c >= delta2.c GROUP BY delta1.c; DROP VIEW rle1; CREATE VIEW rle1 AS SELECT SUM(x)/x AS a, x AS b, c AS c FROM rle0 GROUP BY v; DROP VIEW rle2; CREATE VIEW rle2 AS SELECT a AS v, 1 AS o, 2*c+0 AS c FROM rle1 UNION SELECT b AS v, 1 AS o, 2*c+1 AS c FROM rle1; DROP VIEW normed; CREATE VIEW normed AS SELECT r1.v AS v, SUM(r2.o) AS c FROM rle2 AS r1, rle2 AS r2 WHERE r1.c >= r2.c GROUP BY r1.c; DROP TABLE rle; CREATE TABLE rle(v INT, c INT); INSERT INTO rle SELECT * FROM normed ORDER BY c; DELETE FROM SEQUENCE; INSERT INTO SEQUENCE VALUES(-1,0); INSERT INTO SEQUENCE SELECT * FROM rle;
642Look-and-say sequence
19sql
le0c0
package main import ( "fmt" "github.com/biogo/biogo/align" ab "github.com/biogo/biogo/alphabet" "github.com/biogo/biogo/feat" "github.com/biogo/biogo/seq/linear" ) func main() {
648Levenshtein distance/Alignment
0go
6kh3p
package main import ( "fmt" "log" "math" "rcu" ) var limit = int(math.Sqrt(1e9)) var primes = rcu.Primes(limit) var memoPhi = make(map[int]int) func cantorPair(x, y int) int { if x < 0 || y < 0 { log.Fatal("Arguments must be non-negative integers.") } return (x*x + 3*x + 2*x*y + y + y*y) / 2 } func phi(x, a int) int { if a == 0 { return x } key := cantorPair(x, a) if v, ok := memoPhi[key]; ok { return v } pa := primes[a-1] memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1) return memoPhi[key] } func pi(n int) int { if n < 2 { return 0 } a := pi(int(math.Sqrt(float64(n)))) return phi(n, a) + a - 1 } func main() { for i, n := 0, 1; i <= 9; i, n = i+1, n*10 { fmt.Printf("10^%d %d\n", i, pi(n)) } }
649Legendre prime counting function
0go
cap9g
costs :: String -> String -> [[Int]] costs s1 s2 = reverse $ reverse <$> matrix where matrix = scanl transform [0 .. length s1] s2 transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1 where calc z (c1, x, y) = minimum [ y + 1, z + 1 , x + fromEnum (c1 /= c)] levenshteinDistance :: String -> String -> Int levenshteinDistance s1 s2 = head.head $ costs s1 s2
648Levenshtein distance/Alignment
8haskell
jni7g
func lookAndSay(_ seq: [Int]) -> [Int] { var result = [Int]() var cur = seq[0] var curRunLength = 1 for i in seq.dropFirst() { if cur == i { curRunLength += 1 } else { result.append(curRunLength) result.append(cur) curRunLength = 1 cur = i } } result.append(curRunLength) result.append(cur) return result } var seq = [1] for i in 0..<10 { print("Seq \(i): \(seq)") seq = lookAndSay(seq) }
642Look-and-say sequence
17swift
t7pfl
for(i in 0:4) { s <- "" for(j in 0:i) { s <- paste(s, "*", sep="") } print(s) }
630Loops/For
13r
dgont
import java.util.*; public class LegendrePrimeCounter { public static void main(String[] args) { LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000); for (int i = 0, n = 1; i < 10; ++i, n *= 10) System.out.printf("10^%d\t%d\n", i, counter.primeCount((n))); } private List<Integer> primes; private Map<Integer, Map<Integer, Integer>> phiCache = new HashMap<>(); public LegendrePrimeCounter(int limit) { primes = generatePrimes((int)Math.sqrt((double)limit)); } public int primeCount(int n) { if (n < 2) return 0; int a = primeCount((int)Math.sqrt((double)n)); return phi(n, a) + a - 1; } private int phi(int x, int a) { if (a == 0) return x; Map<Integer, Integer> map = phiCache.computeIfAbsent(x, k -> new HashMap<>()); Integer value = map.get(a); if (value != null) return value; int result = phi(x, a - 1) - phi(x / primes.get(a - 1), a - 1); map.put(a, result); return result; } private static List<Integer> generatePrimes(int limit) { boolean[] sieve = new boolean[limit >> 1]; Arrays.fill(sieve, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; } s += (p + 1) << 2; } List<Integer> primes = new ArrayList<>(); if (limit > 2) primes.add(2); for (int i = 1; i < sieve.length; ++i) { if (sieve[i]) primes.add((i << 1) + 1); } return primes; } }
649Legendre prime counting function
9java
ro0g0
data Memo a = Node a (Memo a) (Memo a) deriving Functor memo :: Integral a => Memo p -> a -> p memo (Node a l r) n | n == 0 = a | odd n = memo l (n `div` 2) | otherwise = memo r (n `div` 2 - 1) nats :: Integral a => Memo a nats = Node 0 ((+1).(*2) <$> nats) ((*2).(+1) <$> nats) memoize :: Integral a => (a -> b) -> a -> b memoize f = memo (f <$> nats) memoize2 :: (Integral a, Integral b) => (a -> b -> c) -> a -> b -> c memoize2 f = memoize (memoize . f) memoList :: [b] -> Integer -> b memoList = memo . mkList where mkList (x:xs) = Node x (mkList l) (mkList r) where (l,r) = split xs split [] = ([],[]) split [x] = ([x],[]) split (x:y:xs) = let (l,r) = split xs in (x:l, y:r)
649Legendre prime counting function
8haskell
pzfbt
public class LevenshteinAlignment { public static String[] alignment(String a, String b) { a = a.toLowerCase(); b = b.toLowerCase();
648Levenshtein distance/Alignment
9java
uqxvv
null
648Levenshtein distance/Alignment
11kotlin
91pmh
>>> print ( '\n'.join(''.join(x) for x in zip('abc', 'ABC', '123')) ) aA1 bB2 cC3 >>>
644Loop over multiple arrays simultaneously
3python
t7kfw
use strict; use warnings; no warnings qw(recursion); use ntheory qw( nth_prime prime_count ); my (%cachephi, %cachepi); sub phi { return $cachephi{"@_"} //= do { my ($x, $aa) = @_; $aa <= 0 ? $x : phi($x, $aa - 1) - phi(int $x / nth_prime($aa), $aa - 1) }; } sub pi { return $cachepi{$_[0]} //= do { my $n = shift; $n < 2 ? 0 : do{ my $aa = pi(int sqrt $n); phi($n, $aa) + $aa - 1 } }; } print "e n Legendre ntheory\n", "- - -------- -------\n"; for (1 .. 9) { printf "%d %12d%10d%10d\n", $_, 10**$_, pi(10**$_), prime_count(10**$_); }
649Legendre prime counting function
2perl
02cs4
use strict; use warnings; use List::Util qw(min); sub levenshtein_distance_alignment { my @s = ('^', split //, shift); my @t = ('^', split //, shift); my @A; @{$A[$_][0]}{qw(d s t)} = ($_, join('', @s[1 .. $_]), ('~' x $_)) for 0 .. $ @{$A[0][$_]}{qw(d s t)} = ($_, ('-' x $_), join '', @t[1 .. $_]) for 0 .. $ for my $i (1 .. $ for my $j (1 .. $ if ($s[$i] ne $t[$j]) { $A[$i][$j]{d} = 1 + ( my $min = min $A[$i-1][$j]{d}, $A[$i][$j-1]{d}, $A[$i-1][$j-1]{d} ); @{$A[$i][$j]}{qw(s t)} = $A[$i-1][$j]{d} == $min ? ($A[$i-1][$j]{s}.$s[$i], $A[$i-1][$j]{t}.'-') : $A[$i][$j-1]{d} == $min ? ($A[$i][$j-1]{s}.'-', $A[$i][$j-1]{t}.$t[$j]) : ($A[$i-1][$j-1]{s}.$s[$i], $A[$i-1][$j-1]{t}.$t[$j]); } else { @{$A[$i][$j]}{qw(d s t)} = ( $A[$i-1][$j-1]{d}, $A[$i-1][$j-1]{s}.$s[$i], $A[$i-1][$j-1]{t}.$t[$j] ); } } } return @{$A[-1][-1]}{'s', 't'}; } print join "\n", levenshtein_distance_alignment "rosettacode", "raisethysword";
648Levenshtein distance/Alignment
2perl
wmye6
multiloop <- function(...) { arguments <- lapply(list(...), as.character) lengths <- sapply(arguments, length) for(i in seq_len(max(lengths))) { for(j in seq_len(nargs())) { cat(ifelse(i <= lengths[j], arguments[[j]][i], " ")) } cat("\n") } } multiloop(letters[1:3], LETTERS[1:3], 1:3)
644Loop over multiple arrays simultaneously
13r
i5ro5
from primesieve import primes from math import isqrt from functools import cache p = primes(isqrt(1_000_000_000)) @cache def phi(x, a): res = 0 while True: if not a or not x: return x + res a -= 1 res -= phi(x def legpi(n): if n < 2: return 0 a = legpi(isqrt(n)) return phi(n, a) + a - 1 for e in range(10): print(f'10^{e}', legpi(10**e))
649Legendre prime counting function
3python
8vl0o
from difflib import ndiff def levenshtein(str1, str2): result = pos, removed = 0, 0 for x in ndiff(str1, str2): if pos<len(str1) and str1[pos] == x[2]: pos += 1 result += x[2] if x[0] == : removed += 1 continue else: if removed > 0: removed -=1 else: result += print(result) levenshtein(,) levenshtein(,)
648Levenshtein distance/Alignment
3python
x9mwr
import Foundation 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, *) } } func eratosthenes(limit: Int) -> [Int] { guard limit >= 3 else { return limit < 2? []: [2] } let ndxLimit = (limit - 3) / 2 + 1 let bufSize = ((limit - 3) / 2) / 32 + 1 let sqrtNdxLimit = (Int(Double(limit).squareRoot()) - 3) / 2 + 1 var cmpsts = Array(repeating: 0, count: bufSize) for ndx in 0..<sqrtNdxLimit where (cmpsts[ndx >> 5] & (1 << (ndx & 31))) == 0 { let p = ndx + ndx + 3 var cullPos = (p * p - 3) / 2 while cullPos < ndxLimit { cmpsts[cullPos >> 5] |= 1 << (cullPos & 31) cullPos += p } } return (-1..<ndxLimit).compactMap({i -> Int? in if i < 0 { return 2 } else { if cmpsts[i >> 5] & (1 << (i & 31)) == 0 { return .some(i + i + 3) } else { return nil } } }) } let primes = eratosthenes(limit: 1_000_000_000) func (_ x: Int, _ a: Int) -> Int { struct Cache { static var cache = [String: Int]() } guard a!= 0 else { return x } guard Cache.cache["\(x),\(a)"] == nil else { return Cache.cache["\(x),\(a)"]! } Cache.cache["\(x),\(a)"] = (x, a - 1) - (x / primes[a - 1], a - 1) return Cache.cache["\(x),\(a)"]! } func (n: Int) -> Int { guard n > 2 else { return 0 } let a = (n: Int(Double(n).squareRoot())) return (n, a) + a - 1 } for i in 0..<10 { let n = 10.power(i) print("(10^\(i)) = \((n: n))") }
649Legendre prime counting function
17swift
ou28k
require 'lcs' def levenshtein_align(a, b) apos, bpos = LCS.new(a, b).backtrack2 c = d = x0 = y0 = -1 dx = dy = 0 apos.zip(bpos) do |x,y| diff = x + dx - y - dy if diff < 0 dx -= diff c += * (-diff) elsif diff > 0 dy += diff d += * diff end c += a[x0+1..x] x0 = x d += b[y0+1..y] y0 = y end c += a[x0+1..-1] d += b[y0+1..-1] diff = a.length + y0 - b.length - x0 if diff < 0 c += * (-diff) elsif diff > 0 d += * diff end [c, d] end puts levenshtein_align(, )
648Levenshtein distance/Alignment
14ruby
slcqw
puts (1..5).map { |i| * i }
630Loops/For
14ruby
ybz6n
[dependencies] edit-distance = "^1.0.0"
648Levenshtein distance/Alignment
15rust
02lsl
import scala.collection.mutable import scala.collection.parallel.ParSeq object LevenshteinAlignment extends App { val vlad = new Levenshtein("rosettacode", "raisethysword") val alignment = vlad.revLevenstein() class Levenshtein(s1: String, s2: String) { val memoizedCosts = mutable.Map[(Int, Int), Int]() def revLevenstein(): (String, String) = { def revLev: (Int, Int, String, String) => (String, String) = { case (_, 0, revS1, revS2) => (revS1, revS2) case (0, _, revS1, revS2) => (revS1, revS2) case (i, j, revS1, revS2) => if (memoizedCosts(i, j) == (memoizedCosts(i - 1, j - 1) + (if (s1(i - 1) != s2(j - 1)) 1 else 0))) revLev(i - 1, j - 1, s1(i - 1) + revS1, s2(j - 1) + revS2) else if (memoizedCosts(i, j) == 1 + memoizedCosts(i - 1, j)) revLev(i - 1, j, s1(i - 1) + revS1, "-" + revS2) else revLev(i, j - 1, "-" + revS1, s2(j - 1) + revS2) } revLev(s1.length, s2.length, "", "") } private def levenshtein: Int = { def lev: ((Int, Int)) => Int = { case (k1, k2) => memoizedCosts.getOrElseUpdate((k1, k2), (k1, k2) match { case (i, 0) => i case (0, j) => j case (i, j) => ParSeq(1 + lev((i - 1, j)), 1 + lev((i, j - 1)), lev((i - 1, j - 1)) + (if (s1(i - 1) != s2(j - 1)) 1 else 0)).min }) } lev((s1.length, s2.length)) } levenshtein } println(alignment._1) println(alignment._2) }
648Levenshtein distance/Alignment
16scala
i5uox
fn main() { for i in 0..5 { for _ in 0..=i { print!("*"); } println!(); } }
630Loops/For
15rust
mp3ya
['a','b','c'].zip(['A','B','C'], [1,2,3]) {|i,j,k| puts }
644Loop over multiple arrays simultaneously
14ruby
3hpz7
for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); }
650List comprehensions
5c
cab9c
fn main() { let a1 = ["a", "b", "c"]; let a2 = ["A", "B", "C"]; let a3 = [1, 2, 3]; for ((&x, &y), &z) in a1.iter().zip(a2.iter()).zip(a3.iter()) { println!("{}{}{}", x, y, z); } }
644Loop over multiple arrays simultaneously
15rust
6k13l
for (i <- 1 to 5) { for (j <- 1 to i) print("*") println() }
630Loops/For
16scala
lemcq
(defn pythagorean-triples [n] (for [x (range 1 (inc n)) y (range x (inc n)) z (range y (inc n)) :when (= (+ (* x x) (* y y)) (* z z))] [x y z]))
650List comprehensions
6clojure
5swuz
("abc", "ABC", "123").zipped foreach { (x, y, z) => println(x.toString + y + z) }
644Loop over multiple arrays simultaneously
16scala
91wm5
function leonardo_number () { L0_value=${2:-1} L1_value=${3:-1} Add=${4:-1} leonardo_numbers=($L0_value $L1_value) for (( i = 2; i < $1; ++i)) do leonardo_numbers+=( $((leonardo_numbers[i-1] + leonardo_numbers[i-2] + Add)) ) done echo "${leonardo_numbers[*]}" }
651Leonardo numbers
4bash
91hms
let a1 = ["a", "b", "c"] let a2 = ["A", "B", "C"] let a3 = [1, 2, 3] for i in 0 ..< a1.count { println("\(a1[i])\(a2[i])\(a3[i])") }
644Loop over multiple arrays simultaneously
17swift
zjbtu
void leonardo(int a,int b,int step,int num){ int i,temp; printf(); for(i=1;i<=num;i++){ if(i==1) printf(,a); else if(i==2) printf(,b); else{ printf(,a+b+step); temp = a; a = b; b = temp+b+step; } } } int main() { int a,b,step; printf(); scanf(,&a,&b,&step); leonardo(a,b,step,25); return 0; }
651Leonardo numbers
5c
lebcy
package main import "fmt" type ( seq []int sofs []seq ) func newSeq(start, end int) seq { if end < start { end = start } s := make(seq, end-start+1) for i := 0; i < len(s); i++ { s[i] = start + i } return s } func newSofs() sofs { return sofs{seq{}} } func (s sofs) listComp(in seq, expr func(sofs, seq) sofs, pred func(seq) bool) sofs { var s2 sofs for _, t := range expr(s, in) { if pred(t) { s2 = append(s2, t) } } return s2 } func (s sofs) build(t seq) sofs { var u sofs for _, ss := range s { for _, tt := range t { uu := make(seq, len(ss)) copy(uu, ss) uu = append(uu, tt) u = append(u, uu) } } return u } func main() { pt := newSofs() in := newSeq(1, 20) expr := func(s sofs, t seq) sofs { return s.build(t).build(t).build(t) } pred := func(t seq) bool { if len(t) != 3 { return false } return t[0]*t[0]+t[1]*t[1] == t[2]*t[2] && t[0] < t[1] && t[1] < t[2] } pt = pt.listComp(in, expr, pred) fmt.Println(pt) }
650List comprehensions
0go
wm3eg
null
644Loop over multiple arrays simultaneously
20typescript
rodg9
pyth :: Int -> [(Int, Int, Int)] pyth n = [ (x, y, z) | x <- [1 .. n] , y <- [x .. n] , z <- [y .. n] , x ^ 2 + y ^ 2 == z ^ 2 ]
650List comprehensions
8haskell
6k73k
for i in 1...5 { for _ in 1...i { print("*", terminator: "") } print() }
630Loops/For
17swift
6kt3j
package main import "fmt" func leonardo(n, l0, l1, add int) []int { leo := make([]int, n) leo[0] = l0 leo[1] = l1 for i := 2; i < n; i++ { leo[i] = leo[i - 1] + leo[i - 2] + add } return leo } func main() { fmt.Println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:") fmt.Println(leonardo(25, 1, 1, 1)) fmt.Println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:") fmt.Println(leonardo(25, 0, 1, 0)) }
651Leonardo numbers
0go
x93wf
import Data.List (intercalate, unfoldr) import Data.List.Split (chunksOf) leo :: Integer -> Integer -> Integer -> [Integer] leo l0 l1 d = unfoldr (\(x, y) -> Just (x, (y, x + y + d))) (l0, l1) leonardo :: [Integer] leonardo = leo 1 1 1 fibonacci :: [Integer] fibonacci = leo 0 1 0 main :: IO () main = (putStrLn . unlines) [ "First 25 default (1, 1, 1) Leonardo numbers:\n" , f $ take 25 leonardo , "First 25 of the (0, 1, 0) Leonardo numbers (= Fibonacci numbers):\n" , f $ take 25 fibonacci ] where f = unlines . fmap (('\t':) . intercalate ",") . chunksOf 16 . fmap show
651Leonardo numbers
8haskell
yb766
void mpz_left_fac_ui(mpz_t rop, unsigned long op) { mpz_t t1; mpz_init_set_ui(t1, 1); mpz_set_ui(rop, 0); size_t i; for (i = 1; i <= op; ++i) { mpz_add(rop, rop, t1); mpz_mul_ui(t1, t1, i); } mpz_clear(t1); } size_t mpz_digitcount(mpz_t op) { char *t = mpz_get_str(NULL, 10, op); size_t ret = strlen(t); free(t); return ret; } int main(void) { mpz_t t; mpz_init(t); size_t i; for (i = 0; i <= 110; ++i) { if (i <= 10 || i % 10 == 0) { mpz_left_fac_ui(t, i); gmp_printf(, i, t); } } for (i = 1000; i <= 10000; i += 1000) { mpz_left_fac_ui(t, i); printf(, i, mpz_digitcount(t)); } mpz_clear(t); return 0; }
652Left factorials
5c
zj5tx
import java.util.Arrays; import java.util.List; @SuppressWarnings("SameParameterValue") public class LeonardoNumbers { private static List<Integer> leonardo(int n) { return leonardo(n, 1, 1, 1); } private static List<Integer> leonardo(int n, int l0, int l1, int add) { Integer[] leo = new Integer[n]; leo[0] = l0; leo[1] = l1; for (int i = 2; i < n; i++) { leo[i] = leo[i - 1] + leo[i - 2] + add; } return Arrays.asList(leo); } public static void main(String[] args) { System.out.println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:"); System.out.println(leonardo(25)); System.out.println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:"); System.out.println(leonardo(25, 0, 1, 0)); } }
651Leonardo numbers
9java
dgvn9
null
650List comprehensions
9java
n4vih
const leoNum = (c, l0 = 1, l1 = 1, add = 1) => new Array(c).fill(add).reduce( (p, c, i) => i > 1 ? ( p.push(p[i - 1] + p[i - 2] + c) && p ) : p, [l0, l1] ); console.log(leoNum(25)); console.log(leoNum(25, 0, 1, 0));
651Leonardo numbers
10javascript
6kr38
null
650List comprehensions
10javascript
3hrz0
for (let i: number = 0; i < 5; ++i) { let line: string = "" for(let j: number = 0; j <= i; ++j) { line += "*" } console.log(line) }
630Loops/For
20typescript
jng7l
int rand(); int rseed = 0; inline void srand(int x) { rseed = x; } inline int rand() { return rseed = (rseed * 1103515245 + 12345) & RAND_MAX; } inline int rand() { return (rseed = (rseed * 214013 + 2531011) & RAND_MAX_32) >> 16; } int main() { int i; printf(, RAND_MAX); for (i = 0; i < 100; i++) printf(, rand()); return 0; }
653Linear congruential generator
5c
6k432
(ns left-factorial (:gen-class)) (defn left-factorial [n] " Compute by updating the state [fact summ] for each k, where k equals 1 to n Update is next state is [k*fact (summ+k)" (second (reduce (fn [[fact summ] k] [(*' fact k) (+ summ fact)]) [1 0] (range 1 (inc n))))) (doseq [n (range 11)] (println (format "!%-3d =%5d" n (left-factorial n)))) (doseq [n (range 20 111 10)] (println (format "!%-3d =%5d" n (biginteger (left-factorial n))))) (doseq [n (range 1000 10001 1000)] (println (format "!%-5d has%5d digits" n (count (str (biginteger (left-factorial n)))))))
652Left factorials
6clojure
91jma
null
651Leonardo numbers
11kotlin
02msf
function leoNums (n, L0, L1, add) local L0, L1, add = L0 or 1, L1 or 1, add or 1 local lNums, nextNum = {L0, L1} while #lNums < n do nextNum = lNums[#lNums] + lNums[#lNums - 1] + add table.insert(lNums, nextNum) end return lNums end function show (msg, t) print(msg .. ":") for i, x in ipairs(t) do io.write(x .. " ") end print("\n") end show("Leonardo numbers", leoNums(25)) show("Fibonacci numbers", leoNums(25, 0, 1, 0))
651Leonardo numbers
1lua
8v90e
null
650List comprehensions
11kotlin
slmq7
(defn iterator [a b] (fn[x] (mod (+ (* a x) b) (bit-shift-left 1 31)))) (def bsd (drop 1 (iterate (iterator 1103515245 12345) 0))) (def ms (drop 1 (for [x (iterate (iterator 214013 2531011) 0)] (bit-shift-right x 16)))) (take 10 bsd) (take 10 ms)
653Linear congruential generator
6clojure
lehcb
no warnings 'experimental::signatures'; use feature 'signatures'; sub leonardo ($n, $l0 = 1, $l1 = 1, $add = 1) { ($l0, $l1) = ($l1, $l0+$l1+$add) for 1..$n; $l0; } my @L = map { leonardo($_) } 0..24; print "Leonardo[1,1,1]: @L\n"; my @F = map { leonardo($_,0,1,0) } 0..24; print "Leonardo[0,1,0]: @F\n";
651Leonardo numbers
2perl
5seu2
LC={} LC.__index = LC function LC:new(o) o = o or {} setmetatable(o, self) return o end function LC:add_iter(func) local prev_iter = self.iter self.iter = coroutine.wrap( (prev_iter == nil) and (function() func{} end) or (function() for arg in prev_iter do func(arg) end end)) return self end function maybe_call(maybe_func, arg) if type(maybe_func) == "function" then return maybe_func(arg) end return maybe_func end function LC:range(key, first, last) return self:add_iter(function(arg) for value=maybe_call(first, arg), maybe_call(last, arg) do arg[key] = value coroutine.yield(arg) end end) end function LC:where(pred) return self:add_iter(function(arg) if pred(arg) then coroutine.yield(arg) end end) end
650List comprehensions
1lua
029sd
package main import ( "fmt" "math/rand" "time" ) type ( vector []int matrix []vector cube []matrix ) func toReduced(m matrix) matrix { n := len(m) r := make(matrix, n) for i := 0; i < n; i++ { r[i] = make(vector, n) copy(r[i], m[i]) } for j := 0; j < n-1; j++ { if r[0][j] != j { for k := j + 1; k < n; k++ { if r[0][k] == j { for i := 0; i < n; i++ { r[i][j], r[i][k] = r[i][k], r[i][j] } break } } } } for i := 1; i < n-1; i++ { if r[i][0] != i { for k := i + 1; k < n; k++ { if r[k][0] == i { for j := 0; j < n; j++ { r[i][j], r[k][j] = r[k][j], r[i][j] } break } } } } return r }
654Latin Squares in reduced form/Randomizing using Jacobson and Matthews’ Technique
0go
x9fwf
int main(void) { static char description[3][80] = { , , }; static int coeff[3] = { 0, 1, -1 }; for (int k = 0; k < 3; k++) { int counter = 0; for (int a = 1; a <= MAX_SIDE_LENGTH; a++) for (int b = 1; b <= a; b++) for (int c = 1; c <= MAX_SIDE_LENGTH; c++) if (a * a + b * b - coeff[k] * a * b == c * c) { counter++; printf(, a, b, c); } printf(, description[k], counter); } return 0; }
655Law of cosines - triples
5c
7ierg
int levenshtein(const char *s, int ls, const char *t, int lt) { int a, b, c; if (!ls) return lt; if (!lt) return ls; if (s[ls - 1] == t[lt - 1]) return levenshtein(s, ls - 1, t, lt - 1); a = levenshtein(s, ls - 1, t, lt - 1); b = levenshtein(s, ls, t, lt - 1); c = levenshtein(s, ls - 1, t, lt ); if (a > b) a = b; if (a > c) a = c; return a + 1; } int main() { const char *s1 = ; const char *s2 = ; printf(, s1, s2, levenshtein(s1, strlen(s1), s2, strlen(s2))); return 0; }
656Levenshtein distance
5c
fr9d3
def Leonardo(L_Zero, L_One, Add, Amount): terms = [L_Zero,L_One] while len(terms) < Amount: new = terms[-1] + terms[-2] new += Add terms.append(new) return terms out = print for term in Leonardo(1,1,1,25): out += str(term) + print out out = print for term in Leonardo(0,1,0,25): out += str(term) + print out
651Leonardo numbers
3python
40w5k
leonardo_numbers <- function(add = 1, l0 = 1, l1 = 1, how_many = 25) { result <- c(l0, l1) for (i in 3:how_many) result <- append(result, result[[i - 1]] + result[[i - 2]] + add) result } cat("First 25 Leonardo numbers\n") cat(leonardo_numbers(), "\n") cat("First 25 Leonardo numbers from 0, 1 with add number = 0\n") cat(leonardo_numbers(0, 0, 1), "\n")
651Leonardo numbers
13r
2wplg
package main import ( "fmt" "math/big" ) func main() { fmt.Print("!0 through!10: 0") one := big.NewInt(1) n := big.NewInt(1) f := big.NewInt(1) l := big.NewInt(1) next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) } for ; ; next() { fmt.Print(" ", l) if n.Int64() == 10 { break } } fmt.Println() for { for i := 0; i < 10; i++ { next() } fmt.Printf("!%d:%d\n", n, l) if n.Int64() == 110 { break } } fmt.Println("Lengths of!1000 through!10000 by thousands:") for i := 110; i < 1000; i++ { next() } for { fmt.Print(" ", len(l.String())) if n.Int64() == 10000 { break } for i := 0; i < 1000; i++ { next() } } fmt.Println() }
652Left factorials
0go
kf8hz
(defn levenshtein [str1 str2] (let [len1 (count str1) len2 (count str2)] (cond (zero? len1) len2 (zero? len2) len1 :else (let [cost (if (= (first str1) (first str2)) 0 1)] (min (inc (levenshtein (rest str1) str2)) (inc (levenshtein str1 (rest str2))) (+ cost (levenshtein (rest str1) (rest str2)))))))) (println (levenshtein "rosettacode" "raisethysword"))
656Levenshtein distance
6clojure
ybu6b
leftFact :: [Integer] leftFact = scanl (+) 0 fact fact :: [Integer] fact = scanl (*) 1 [1 ..] main :: IO () main = mapM_ putStrLn [ "0 ~ 10:" , show $ (leftFact !!) <$> [0 .. 10] , "" , "20 ~ 110 by tens:" , unlines $ show . (leftFact !!) <$> [20,30 .. 110] , "" , "length of 1,000 ~ 10,000 by thousands:" , show $ length . show . (leftFact !!) <$> [1000,2000 .. 10000] , "" ]
652Left factorials
8haskell
n4lie
def leonardo(l0=1, l1=1, add=1) return to_enum(__method__,l0,l1,add) unless block_given? loop do yield l0 l0, l1 = l1, l0+l1+add end end p leonardo.take(25) p leonardo(0,1,0).take(25)
651Leonardo numbers
14ruby
roqgs
package main import "fmt" type triple struct{ a, b, c int } var squares13 = make(map[int]int, 13) var squares10000 = make(map[int]int, 10000) func init() { for i := 1; i <= 13; i++ { squares13[i*i] = i } for i := 1; i <= 10000; i++ { squares10000[i*i] = i } } func solve(angle, maxLen int, allowSame bool) []triple { var solutions []triple for a := 1; a <= maxLen; a++ { for b := a; b <= maxLen; b++ { lhs := a*a + b*b if angle != 90 { switch angle { case 60: lhs -= a * b case 120: lhs += a * b default: panic("Angle must be 60, 90 or 120 degrees") } } switch maxLen { case 13: if c, ok := squares13[lhs]; ok { if !allowSame && a == b && b == c { continue } solutions = append(solutions, triple{a, b, c}) } case 10000: if c, ok := squares10000[lhs]; ok { if !allowSame && a == b && b == c { continue } solutions = append(solutions, triple{a, b, c}) } default: panic("Maximum length must be either 13 or 10000") } } } return solutions } func main() { fmt.Print("For sides in the range [1, 13] ") fmt.Println("where they can all be of the same length:-\n") angles := []int{90, 60, 120} var solutions []triple for _, angle := range angles { solutions = solve(angle, 13, true) fmt.Printf(" For an angle of%d degrees", angle) fmt.Println(" there are", len(solutions), "solutions, namely:") fmt.Printf(" %v\n", solutions) fmt.Println() } fmt.Print("For sides in the range [1, 10000] ") fmt.Println("where they cannot ALL be of the same length:-\n") solutions = solve(60, 10000, false) fmt.Print(" For an angle of 60 degrees") fmt.Println(" there are", len(solutions), "solutions.") }
655Law of cosines - triples
0go
dg9ne
sub triples ($) { my ($n) = @_; map { my $x = $_; map { my $y = $_; map { [$x, $y, $_] } grep { $x**2 + $y**2 == $_**2 } 1..$n } 1..$n } 1..$n; }
650List comprehensions
2perl
uqevr
import java.math.BigInteger; public class LeftFac{ public static BigInteger factorial(BigInteger n){ BigInteger ans = BigInteger.ONE; for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){ ans = ans.multiply(x); } return ans; } public static BigInteger leftFact(BigInteger n){ BigInteger ans = BigInteger.ZERO; for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){ ans = ans.add(factorial(k)); } return ans; } public static void main(String[] args){ for(int i = 0; i <= 10; i++){ System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); } for(int i = 20; i <= 110; i += 10){ System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i))); } for(int i = 1000; i <= 10000; i += 1000){ System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits"); } } }
652Left factorials
9java
qc3xa
fn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> { std::iter::from_fn(move || { let n = n0; n0 = n1; n1 += n + add; Some(n) }) } fn main() { println!("First 25 Leonardo numbers:"); for i in leonardo(1, 1, 1).take(25) { print!("{} ", i); } println!(); println!("First 25 Fibonacci numbers:"); for i in leonardo(0, 1, 0).take(25) { print!("{} ", i); } println!(); }
651Leonardo numbers
15rust
7isrc