code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
n = 1024 while n>0 do print(n) n = math.floor(n/2) end
625Loops/While
1lua
xc0wz
for i=10,0,-1 do print(i) end
627Loops/Downward for
1lua
ngdi8
package main import "fmt" func main() { var value int for { value++ fmt.Println(value) if value%6 != 0 { break } } }
629Loops/Do-while
0go
qcwxz
for(i in (2..9).step(2)) { print "${i} " } println "Who do we appreciate?"
628Loops/For with a specified step
7groovy
qlqxp
def i = 0 do { i++ println i } while (i % 6 != 0)
629Loops/Do-while
7groovy
13bp6
import Control.Monad (forM_) main = do forM_ [2,4..8] (\x -> putStr (show x ++ ", ")) putStrLn "who do we appreciate?"
628Loops/For with a specified step
8haskell
vqv2k
for my $i(1..10) { print $i; last if $i == 10; print ', '; } print "\n";
624Loops/N plus one half
2perl
8ud0w
for i in collection: print i
622Loops/Foreach
3python
6b23w
a <- list("First", "Second", "Third", 5, 6) for(i in a) print(i)
622Loops/Foreach
13r
f7mdc
for ($i = 1; $i <= 11; $i++) { echo $i; if ($i == 10) break; echo ', '; } echo ;
624Loops/N plus one half
12php
48j5n
function luhn(n) n=string.reverse(n) print(n) local s1=0
621Luhn test of credit card numbers
1lua
ri1ga
my $a = [ map [ map { int(rand(20)) + 1 } 1 .. 10 ], 1 .. 10]; Outer: foreach (@$a) { foreach (@$_) { print " $_"; if ($_ == 20) { last Outer; } } print "\n"; } print "\n";
623Loops/Nested
2perl
s2nq3
import Data.List import Control.Monad import Control.Arrow doWhile p f n = (n:) $ takeWhile p $ unfoldr (Just.(id &&& f)) $ succ n
629Loops/Do-while
8haskell
mp6yf
struct node { int val, len; struct node *next; }; void lis(int *v, int len) { int i; struct node *p, *n = calloc(len, sizeof *n); for (i = 0; i < len; i++) n[i].val = v[i]; for (i = len; i--; ) { for (p = n + i; p++ < n + len; ) { if (p->val > n[i].val && p->len >= n[i].len) { n[i].next = p; n[i].len = p->len + 1; } } } for (i = 0, p = n; i < len; i++) if (n[i].len > p->len) p = n + i; do printf(, p->val); while ((p = p->next)); putchar('\n'); free(n); } int main(void) { int x[] = { 3, 2, 6, 4, 5, 1 }; int y[] = { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 }; lis(x, sizeof(x) / sizeof(int)); lis(y, sizeof(y) / sizeof(int)); return 0; }
631Longest increasing subsequence
5c
jn470
<?php for ($i = 0; $i < 10; $i++) for ($j = 0; $j < 10; $j++) $a[$i][$j] = rand(1, 20); foreach ($a as $row) { foreach ($row as $element) { echo ; if ($element == 20) break 2; } echo ; } echo ; ?>
623Loops/Nested
12php
us7v5
int cmp(const char *p, const char *q) { while (*p && *q) p = &p[1], q = &q[1]; return *p; } int main() { char line[65536]; char buf[1000000] = {0}; char *last = buf; char *next = buf; while (gets(line)) { strcat(line, ); if (cmp(last, line)) continue; if (cmp(line, last)) next = buf; last = next; strcpy(next, line); while (*next) next = &next[1]; } printf(, buf); return 0; }
632Longest string challenge
5c
a6h11
for i in collection do puts i end
622Loops/Foreach
14ruby
m1uyj
let collection = vec![1,2,3,4,5]; for elem in collection { println!("{}", elem); }
622Loops/Foreach
15rust
9a5mm
int val = 0; do{ val++; System.out.println(val); }while(val % 6 != 0);
629Loops/Do-while
9java
frndv
print ( ', '.join(str(i+1) for i in range(10)) )
624Loops/N plus one half
3python
o5f81
(defn place [piles card] (let [[les gts] (->> piles (split-with #(<= (ffirst %) card))) newelem (cons card (->> les last first)) modpile (cons newelem (first gts))] (concat les (cons modpile (rest gts))))) (defn a-longest [cards] (let [piles (reduce place '() cards)] (->> piles last first reverse))) (println (a-longest [3 2 6 4 5 1])) (println (a-longest [0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15]))
631Longest increasing subsequence
6clojure
13hpy
var val = 0; do { print(++val); } while (val % 6);
629Loops/Do-while
10javascript
yb36r
paste(1:10, collapse=", ")
624Loops/N plus one half
13r
qloxs
ns longest-string (:gen-class)) (defn longer [a b] " if a is longer, it returns the characters in a after length b characters have been removed otherwise it returns nil " (if (or (empty? a) (empty? b)) (not-empty a) (recur (rest a) (rest b)))) (defn get-input [] " Gets the data from standard input as a lazy-sequence of lines (i.e. reads lines as needed by caller Input is terminated by a zero length line (i.e. line with just <CR> " (let [line (read-line)] (if (> (count line) 0) (lazy-seq (cons line (get-input))) nil))) (defn process [] " Returns list of longest lines " (first (reduce (fn [[lines longest] x] (cond (longer x longest) [x x] (not (longer longest x)) [(str lines "\n" x) longest] :else [lines longest])) ["" ""] (get-input)))) (println "Input text:") (println "Output:\n" (process))
632Longest string challenge
6clojure
slaqr
val collection = Array(1, 2, 3, 4) collection.foreach(println)
622Loops/Foreach
16scala
2xrlb
null
629Loops/Do-while
11kotlin
8vs0q
for(int i = 2; i <= 8;i += 2){ System.out.print(i + ", "); } System.out.println("who do we appreciate?");
628Loops/For with a specified step
9java
ypy6g
from random import randint def do_scan(mat): for row in mat: for item in row: print item, if item == 20: print return print print mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)] do_scan(mat)
623Loops/Nested
3python
0vdsq
var output = '', i; for (i = 2; i <= 8; i += 2) { output += i + ', '; } output += 'who do we appreciate?'; document.write(output);
628Loops/For with a specified step
10javascript
2x2lr
void lcs(const char * const sa, const char * const sb, char ** const beg, char ** const end) { size_t apos, bpos; ptrdiff_t len; *beg = 0; *end = 0; len = 0; for (apos = 0; sa[apos] != 0; ++apos) { for (bpos = 0; sb[bpos] != 0; ++bpos) { if (sa[apos] == sb[bpos]) { len = 1; while (sa[apos + len] != 0 && sb[bpos + len] != 0 && sa[apos + len] == sb[bpos + len]) { len++; } } if (len > *end - *beg) { *beg = sa + apos; *end = *beg + len; len = 0; } } } } int main() { char *s1 = ; char *s2 = ; char *beg, *end, *it; lcs(s1, s2, &beg, &end); for (it = beg; it != end; it++) { putchar(*it); } printf(); return 0; }
633Longest common substring
5c
i5xo2
package main import ( "bufio" "os" ) func main() { in := bufio.NewReader(os.Stdin) var blankLine = "\n" var printLongest func(string) string printLongest = func(candidate string) (longest string) { longest = candidate s, err := in.ReadString('\n') defer func() { recover() defer func() { recover() }() _ = blankLine[0] func() { defer func() { recover() }() _ = s[len(longest)] longest = s }() longest = printLongest(longest) func() { defer func() { recover() os.Stdout.WriteString(s) }() _ = longest[len(s)] s = "" }() }() _ = err.(error) os.Stdout.WriteString(blankLine) blankLine = "" return } printLongest("") }
632Longest string challenge
0go
mptyi
m <- 10 n <- 10 mat <- matrix(sample(1:20L, m*n, replace=TRUE), nrow=m); mat done <- FALSE for(i in seq_len(m)) { for(j in seq_len(n)) { cat(mat[i,j]) if(mat[i,j] == 20) { done <- TRUE break } cat(", ") } if(done) { cat("\n") break } }
623Loops/Nested
13r
w98e5
(1..10).each do |i| print i break if i == 10 print end puts
624Loops/N plus one half
14ruby
ngzit
def longer = { a, b -> def aa = a, bb = b while (bb && aa) { bb = bb.substring(1) aa = aa.substring(1) } aa ? a: b } def longestStrings longestStrings = { BufferedReader source, String longest = '' -> String current = source.readLine() def finalLongest = current == null \ ? longest \ : longestStrings(source,longer(current,longest)) if (longer(finalLongest, current) == current) { println current } return finalLongest }
632Longest string challenge
7groovy
t7ofh
for(int i = 1;i <= 10; i++){ printf(, i); if(i % 5 == 0){ printf(); continue; } printf(); }
634Loops/Continue
5c
vx62o
null
628Loops/For with a specified step
11kotlin
f7fdo
fn main() { for i in 1..=10 { print!("{}{}", i, if i < 10 { ", " } else { "\n" }); } }
624Loops/N plus one half
15rust
dr3ny
module Main where import System.Environment cmp :: String -> String -> Ordering cmp [] [] = EQ cmp [] (_:_) = LT cmp (_:_) [] = GT cmp (_:xs) (_:ys) = cmp xs ys longest :: String -> String longest = longest' "" "" . lines where longest' acc l [] = acc longest' [] l (x:xs) = longest' x x xs longest' acc l (x:xs) = case cmp l x of LT -> longest' x x xs EQ -> longest' (acc ++ '\n':x) l xs GT -> longest' acc l xs main :: IO () main = do (file:_) <- getArgs contents <- readFile file putStrLn $ longest contents
632Longest string challenge
8haskell
kfgh0
package main import ( "fmt" "sort" ) type Node struct { val int back *Node } func lis (n []int) (result []int) { var pileTops []*Node
631Longest increasing subsequence
0go
frod0
var i = 1 while ({ print(i) i < 10 }) { print(", ") i += 1 } println()
624Loops/N plus one half
16scala
zhmtr
typedef int bool; void sieve(int limit, int primes[], int *count) { bool *c = calloc(limit + 1, sizeof(bool)); int i, p = 3, p2, n = 0; p2 = p * p; while (p2 <= limit) { for (i = p2; i <= limit; i += 2 * p) c[i] = TRUE; do { p += 2; } while (c[p]); p2 = p * p; } for (i = 3; i <= limit; i += 2) { if (!c[i]) primes[n++] = i; } *count = n; free(c); } int findPeriod(int n) { int i, r = 1, rr, period = 0; for (i = 1; i <= n + 1; ++i) { r = (10 * r) % n; } rr = r; do { r = (10 * r) % n; period++; } while (r != rr); return period; } int main() { int i, prime, count = 0, index = 0, primeCount, longCount = 0, numberCount; int *primes, *longPrimes, *totals; int numbers[] = {500, 1000, 2000, 4000, 8000, 16000, 32000, 64000}; primes = calloc(6500, sizeof(int)); numberCount = sizeof(numbers) / sizeof(int); totals = calloc(numberCount, sizeof(int)); sieve(64000, primes, &primeCount); longPrimes = calloc(primeCount, sizeof(int)); for (i = 0; i < primeCount; ++i) { prime = primes[i]; if (findPeriod(prime) == prime - 1) { longPrimes[longCount++] = prime; } } for (i = 0; i < longCount; ++i, ++count) { if (longPrimes[i] > numbers[index]) { totals[index++] = count; } } totals[numberCount - 1] = count; printf(, numbers[0]); printf(); for (i = 0; i < totals[0]; ++i) { printf(, longPrimes[i]); } printf(); printf(); for (i = 0; i < 8; ++i) { printf(, numbers[i], totals[i]); } free(totals); free(longPrimes); free(primes); return 0; }
635Long primes
5c
91dm1
import java.io.File; import java.util.Scanner; public class LongestStringChallenge { public static void main(String[] args) throws Exception { String lines = "", longest = ""; try (Scanner sc = new Scanner(new File("lines.txt"))) { while(sc.hasNext()) { String line = sc.nextLine(); if (longer(longest, line)) lines = longest = line; else if (!longer(line, longest)) lines = lines.concat("\n").concat(line); } } System.out.println(lines); } static boolean longer(String a, String b) { try { String dummy = a.substring(b.length()); } catch (StringIndexOutOfBoundsException e) { return true; } return false; } }
632Longest string challenge
9java
40l58
import Data.Ord ( comparing ) import Data.List ( maximumBy, subsequences ) import Data.List.Ordered ( isSorted, nub ) lis :: Ord a => [a] -> [a] lis = maximumBy (comparing length) . map nub . filter isSorted . subsequences main = do print $ lis [3,2,6,4,5,1] print $ lis [0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15] print $ lis [1,1,1,1]
631Longest increasing subsequence
8haskell
4025s
while(1){ print "SPAM\n"; }
626Loops/Infinite
2perl
go74e
i=0 repeat i=i+1 print(i) until i%6 == 0
629Loops/Do-while
1lua
ou08h
null
632Longest string challenge
11kotlin
le6cp
(doseq [n (range 1 11)] (print n) (if (zero? (rem n 5)) (println) (print ", ")))
634Loops/Continue
6clojure
rolg2
for i in [1,2,3] { print(i) }
622Loops/Foreach
17swift
ypv6e
while(1) echo ;
626Loops/Infinite
12php
ngfig
foreach (reverse 0..10) { print "$_\n"; }
627Loops/Downward for
2perl
ri7gd
ary = (1..20).to_a.shuffle.each_slice(4).to_a p ary catch :found_it do for row in ary for element in row print % element throw :found_it if element == 20 end puts end end puts
623Loops/Nested
14ruby
o5t8v
for ($i = 10; $i >= 0; $i--) echo ;
627Loops/Downward for
12php
drfn8
int p(int year) { return (int)((double)year + floor(year/4) - floor(year/100) + floor(year/400)) % 7; } int is_long_year(int year) { return p(year) == 4 || p(year - 1) == 3; } void print_long_years(int from, int to) { for (int year = from; year <= to; ++year) { if (is_long_year(year)) { printf(, year); } } } int main() { printf(); print_long_years(1800, 2100); printf(); return 0; }
636Long year
5c
mpiys
int lcs (char *a, int n, char *b, int m, char **s) { int i, j, k, t; int *z = calloc((n + 1) * (m + 1), sizeof (int)); int **c = calloc((n + 1), sizeof (int *)); for (i = 0; i <= n; i++) { c[i] = &z[i * (m + 1)]; } for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { if (a[i - 1] == b[j - 1]) { c[i][j] = c[i - 1][j - 1] + 1; } else { c[i][j] = MAX(c[i - 1][j], c[i][j - 1]); } } } t = c[n][m]; *s = malloc(t); for (i = n, j = m, k = t - 1; k >= 0;) { if (a[i - 1] == b[j - 1]) (*s)[k] = a[i - 1], i--, j--, k--; else if (c[i][j - 1] > c[i - 1][j]) j--; else i--; } free(c); free(z); return t; }
637Longest common subsequence
5c
4065t
function longer(s1, s2) while true do s1 = s1:sub(1, -2) s2 = s2:sub(1, -2) if s1:find('^$') and not s2:find('^$') then return false elseif s2:find('^$') then return true end end end local output = '' local longest = '' for line in io.lines() do local islonger = longer(line, longest) if islonger and longer(longest, line) then output = output .. line .. '\n' elseif islonger then longest = line output = line .. '\n' end end print(output)
632Longest string challenge
1lua
2wyl3
import java.util.*; public class LIS { public static <E extends Comparable<? super E>> List<E> lis(List<E> n) { List<Node<E>> pileTops = new ArrayList<Node<E>>();
631Longest increasing subsequence
9java
ca69h
use rand::Rng; extern crate rand; fn main() { let mut matrix = [[0u8; 10]; 10]; let mut rng = rand::thread_rng(); for row in matrix.iter_mut() { for item in row.iter_mut() { *item = rng.gen_range(0, 21); } } 'outer: for row in matrix.iter() { for &item in row.iter() { print!("{:2} ", item); if item == 20 { break 'outer } } println!(); } }
623Loops/Nested
15rust
i4zod
typedef unsigned int uint; typedef unsigned long long tree; tree *list = 0; uint cap = 0, len = 0; uint offset[32] = {0, 1, 0}; void append(tree t) { if (len == cap) { cap = cap ? cap*2 : 2; list = realloc(list, cap*sizeof(tree)); } list[len++] = 1 | t<<1; } void show(tree t, uint len) { for (; len--; t >>= 1) putchar(t&1 ? '(' : ')'); } void listtrees(uint n) { uint i; for (i = offset[n]; i < offset[n+1]; i++) { show(list[i], n*2); putchar('\n'); } } void assemble(uint n, tree t, uint sl, uint pos, uint rem) { if (!rem) { append(t); return; } if (sl > rem) pos = offset[sl = rem]; else if (pos >= offset[sl + 1]) { if (!--sl) return; pos = offset[sl]; } assemble(n, t<<(2*sl) | list[pos], sl, pos, rem - sl); assemble(n, t, sl, pos + 1, rem); } void mktrees(uint n) { if (offset[n + 1]) return; if (n) mktrees(n - 1); assemble(n, 0, n-1, offset[n-1], n-1); offset[n+1] = len; } int main(int c, char**v) { int n; if (c < 2 || (n = atoi(v[1])) <= 0 || n > 25) n = 5; append(0); mktrees((uint)n); fprintf(stderr, , n, offset[n+1] - offset[n]); listtrees((uint)n); return 0; }
638List rooted trees
5c
5szuk
(defn long-year? [year] (-> (java.time.LocalDate/of year 12 28) (.get (.weekOfYear (java.time.temporal.WeekFields/ISO))) (= 53))) (filter long-year? (range 2000 2100))
636Long year
6clojure
vxz2f
function getLis(input) { if (input.length === 0) { return []; } var lisLenPerIndex = []; let max = { index: 0, length: 1 }; for (var i = 0; i < input.length; i++) { lisLenPerIndex[i] = 1; for (var j = i - 1; j >= 0; j--) { if (input[i] > input[j] && lisLenPerIndex[j] >= lisLenPerIndex[i]) { var length = lisLenPerIndex[i] = lisLenPerIndex[j] + 1; if (length > max.length) { max = { index: i, length }; } } } } var lis = [input[max.index]]; for (var i = max.index; i >= 0 && max.length !== 0; i--) { if (input[max.index] > input[i] && lisLenPerIndex[i] === max.length - 1) { lis.unshift(input[i]); max.length--; } } return lis; } console.log(getLongestIncreasingSubsequence([0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])); console.log(getLongestIncreasingSubsequence([3, 2, 6, 4, 5, 1]));
631Longest increasing subsequence
10javascript
5slur
import scala.util.control.Breaks._ val a=Array.fill(5,4)(scala.util.Random.nextInt(21)) println(a map (_.mkString("[", ", ", "]")) mkString "\n") breakable { for(row <- a; x <- row){ println(x) if (x==20) break } }
623Loops/Nested
16scala
f7yd4
for var i = 1;; i++ { print(i) if i == 10 { println() break } print(", ") }
624Loops/N plus one half
17swift
i4to0
((\d*\.\d+|\d+\.)([eE][+-]?[0-9]+)?[flFL]?)|([0-9]+[eE][+-]?[0-9]+[flFL]?)
639Literals/Floating point
5c
qcrxc
int main(){ time_t t; int a, b; srand((unsigned)time(&t)); for(;;){ a = rand() % 20; printf(, a); if(a == 10) break; b = rand() % 20; printf(, b); } return 0; }
640Loops/Break
5c
3hwza
package main import "fmt" func lcs(a, b string) (output string) { lengths := make([]int, len(a)*len(b)) greatestLength := 0 for i, x := range a { for j, y := range b { if x == y { if i == 0 || j == 0 { lengths[i*len(b)+j] = 1 } else { lengths[i*len(b)+j] = lengths[(i-1)*len(b)+j-1] + 1 } if lengths[i*len(b)+j] > greatestLength { greatestLength = lengths[i*len(b)+j] output = a[i-greatestLength+1 : i+1] } } } } return } func main() { fmt.Println(lcs("thisisatest", "testing123testing")) }
633Longest common substring
0go
g8l4n
user=> 1. 1.0 user=> 1.0 1.0 user=> 3.1415 3.1415 user=> 1.234E-10 1.234E-10 user=> 1e100 1.0E100 user=> (Float/valueOf "1.0f") 1.0
639Literals/Floating point
6clojure
i5bom
(defn longest [xs ys] (if (> (count xs) (count ys)) xs ys)) (def lcs (memoize (fn [[x & xs] [y & ys]] (cond (or (= x nil) (= y nil)) nil (= x y) (cons x (lcs xs ys)) :else (longest (lcs (cons x xs) ys) (lcs xs (cons y ys)))))))
637Longest common subsequence
6clojure
hdljr
import Data.Ord (comparing) import Data.List (maximumBy, intersect) subStrings :: [a] -> [[a]] subStrings s = let intChars = length s in [ take n $ drop i s | i <- [0 .. intChars - 1] , n <- [1 .. intChars - i] ] longestCommon :: Eq a => [a] -> [a] -> [a] longestCommon a b = maximumBy (comparing length) (subStrings a `intersect` subStrings b) main :: IO () main = putStrLn $ longestCommon "testing123testing" "thisisatest"
633Longest common substring
8haskell
sl1qk
my $n = 1024; while($n){ print "$n\n"; $n = int $n / 2; }
625Loops/While
2perl
lwuc5
for i in xrange(10, -1, -1): print i
627Loops/Downward for
3python
7njrm
package main import ( "fmt" "regexp" "strings" )
641Long literals, with continuations
0go
n4ki1
elements = words "hydrogen \ \ fluorine neon sodium magnesium \ \ aluminum silicon phosphorous sulfur \ \ chlorine argon potassium calcium \ \ scandium titanium vanadium chromium \ \ manganese iron cobalt nickel \ \ copper zinc gallium germanium \ \ arsenic selenium bromine krypton \ \ rubidium strontium yttrium zirconium \ \ niobium molybdenum technetium ruthenium \ \ rhodium palladium silver cadmium \ \ indium tin antimony tellurium \ \ iodine xenon cesium barium \ \ lanthanum cerium praseodymium neodymium \ \ promethium samarium europium gadolinium \ \ terbium dysprosium holmium erbium \ \ thulium ytterbium lutetium hafnium \ \ tantalum tungsten rhenium osmium \ \ iridium platinum gold mercury \ \ thallium lead bismuth polonium \ \ astatine radon francium radium \ \ actinium thorium protactinium uranium \ \ neptunium plutonium americium curium \ \ berkelium californium einsteinium fermium \ \ mendelevium nobelium lawrencium rutherfordium \ \ dubnium seaborgium bohrium hassium \ \ meitnerium darmstadtium roentgenium copernicium \ \ nihonium flerovium moscovium livermorium \ \ tennessine oganesson"
641Long literals, with continuations
8haskell
uqnv2
package main import ( "fmt" "log" "os" "strconv" ) type tree uint64 var ( list []tree offset = [32]uint{1: 1} ) func add(t tree) { list = append(list, 1|t<<1) } func show(t tree, l uint) { for ; l > 0; t >>= 1 { l-- var paren byte if (t & 1) != 0 { paren = '(' } else { paren = ')' } fmt.Printf("%c", paren) } } func listTrees(n uint) { for i := offset[n]; i < offset[n+1]; i++ { show(list[i], n*2) fmt.Println() } } func assemble(n uint, t tree, sl, pos, rem uint) { if rem == 0 { add(t) return } if sl > rem {
638List rooted trees
0go
8vk0g
null
631Longest increasing subsequence
11kotlin
3hdz5
public class LongestCommonSubstring { public static void main(String[] args) { System.out.println(lcs("testing123testing", "thisisatest")); System.out.println(lcs("test", "thisisatest")); System.out.println(lcs("testing", "sting")); System.out.println(lcs("testing", "thisisasting")); } static String lcs(String a, String b) { if (a.length() > b.length()) return lcs(b, a); String res = ""; for (int ai = 0; ai < a.length(); ai++) { for (int len = a.length() - ai; len > 0; len--) { for (int bi = 0; bi <= b.length() - len; bi++) { if (a.regionMatches(ai, b, bi, len) && len > res.length()) { res = a.substring(ai, ai + len); } } } } return res; } }
633Longest common substring
9java
137p2
sub luhn_test { my @rev = reverse split //,$_[0]; my ($sum1,$sum2,$i) = (0,0,0); for(my $i=0;$i<@rev;$i+=2) { $sum1 += $rev[$i]; last if $i == $ $sum2 += 2*$rev[$i+1]%10 + int(2*$rev[$i+1]/10); } return ($sum1+$sum2) % 10 == 0; } print luhn_test('49927398716'); print luhn_test('49927398717'); print luhn_test('1234567812345678'); print luhn_test('1234567812345670');
621Luhn test of credit card numbers
2perl
ngyiw
while 1: print
626Loops/Infinite
3python
rijgq
for(i in 10:0) {print(i)}
627Loops/Downward for
13r
504uy
for i=2,9,2 do print(i) end
628Loops/For with a specified step
1lua
tjtfn
import java.time.Instant const val elementsChunk = """ hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson """ const val unamedElementsChunk = """ ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium """ fun main() { fun String.splitToList() = trim().split("\\s+".toRegex()); val elementsList = elementsChunk.splitToList() .filterNot(unamedElementsChunk.splitToList().toSet()::contains) println("Last revision Date: ${Instant.now()}") println("Number of elements: ${elementsList.size}") println("Last element : ${elementsList.last()}") println("The elements are : ${elementsList.joinToString(" ", limit = 5)}") }
641Long literals, with continuations
11kotlin
t71f0
parts :: Int -> [[(Int, Int)]] parts n = f n 1 where f n x | n == 0 = [[]] | x > n = [] | otherwise = f n (x + 1) ++ concatMap (\c -> map ((c, x):) (f (n - c * x) (x + 1))) [1 .. n `div` x] pick :: Int -> [String] -> [String] pick _ [] = [] pick 0 _ = [""] pick n aa@(a:as) = map (a ++) (pick (n - 1) aa) ++ pick n as trees :: Int -> [String] trees n = map (\x -> "(" ++ x ++ ")") $ concatMap (foldr (prod . build) [""]) (parts (n - 1)) where build (c, x) = pick c $ trees x prod aa bb = [ a ++ b | a <- aa , b <- bb ] main :: IO () main = mapM_ putStrLn $ trees 5
638List rooted trees
8haskell
lench
package main import ( "fmt" "time" ) func main() { centuries := []string{"20th", "21st", "22nd"} starts := []int{1900, 2000, 2100} for i := 0; i < len(centuries); i++ { var longYears []int fmt.Printf("\nLong years in the%s century:\n", centuries[i]) for j := starts[i]; j < starts[i] + 100; j++ { t := time.Date(j, time.December, 28, 0, 0, 0, 0, time.UTC) if _, week := t.ISOWeek(); week == 53 { longYears = append(longYears, j) } } fmt.Println(longYears) } }
636Long year
0go
a6g1f
END{ print $all } substr($_, length($l)) and $all = $l = $_ or substr($l, length) or $all .= $_;
632Longest string challenge
2perl
qc1x6
function buildLIS(seq) local piles = { { {table.remove(seq, 1), nil} } } while #seq>0 do local x=table.remove(seq, 1) for j=1,#piles do if piles[j][#piles[j]][1]>x then table.insert(piles[j], {x, (piles[j-1] and #piles[j-1])}) break elseif j==#piles then table.insert(piles, {{x, #piles[j]}}) end end end local t={} table.insert(t, piles[#piles][1][1]) local p=piles[#piles][1][2] for i=#piles-1,1,-1 do table.insert(t, piles[i][p][1]) p=piles[i][p][2] end table.sort(t) print(unpack(t)) end buildLIS({3,2,6,4,5,1}) buildLIS({0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15})
631Longest increasing subsequence
1lua
6kf39
(() => { 'use strict';
633Longest common substring
10javascript
qcpx8
let array = [[2, 12, 10, 4], [18, 11, 20, 2]] loop: for row in array { for element in row { println(" \(element)") if element == 20 { break loop } } } print("done")
623Loops/Nested
17swift
8uf0v
repeat print("SPAM")
626Loops/Infinite
13r
us4vx
$i = 1024; while ($i > 0) { echo ; $i >>= 1; }
625Loops/While
12php
ql8x3
revised = "February 2, 2021"
641Long literals, with continuations
1lua
zjaty
import java.util.ArrayList; import java.util.List; public class ListRootedTrees { private static final List<Long> TREE_LIST = new ArrayList<>(); private static final List<Integer> OFFSET = new ArrayList<>(); static { for (int i = 0; i < 32; i++) { if (i == 1) { OFFSET.add(1); } else { OFFSET.add(0); } } } private static void append(long t) { TREE_LIST.add(1 | (t << 1)); } private static void show(long t, int l) { while (l-- > 0) { if (t % 2 == 1) { System.out.print('('); } else { System.out.print(')'); } t = t >> 1; } } private static void listTrees(int n) { for (int i = OFFSET.get(n); i < OFFSET.get(n + 1); i++) { show(TREE_LIST.get(i), n * 2); System.out.println(); } } private static void assemble(int n, long t, int sl, int pos, int rem) { if (rem == 0) { append(t); return; } var pp = pos; var ss = sl; if (sl > rem) { ss = rem; pp = OFFSET.get(ss); } else if (pp >= OFFSET.get(ss + 1)) { ss--; if (ss == 0) { return; } pp = OFFSET.get(ss); } assemble(n, t << (2 * ss) | TREE_LIST.get(pp), ss, pp, rem - ss); assemble(n, t, ss, pp + 1, rem); } private static void makeTrees(int n) { if (OFFSET.get(n + 1) != 0) { return; } if (n > 0) { makeTrees(n - 1); } assemble(n, 0, n - 1, OFFSET.get(n - 1), n - 1); OFFSET.set(n + 1, TREE_LIST.size()); } private static void test(int n) { if (n < 1 || n > 12) { throw new IllegalArgumentException("Argument must be between 1 and 12"); } append(0); makeTrees(n); System.out.printf("Number of%d-trees:%d\n", n, OFFSET.get(n + 1) - OFFSET.get(n)); listTrees(n); } public static void main(String[] args) { test(5); } }
638List rooted trees
9java
3hqzg
import Data.Time.Calendar (fromGregorian) import Data.Time.Calendar.WeekDate (toWeekDate) longYear :: Integer -> Bool longYear y = let (_, w, _) = toWeekDate $ fromGregorian y 12 28 in 52 < w main :: IO () main = mapM_ print $ filter longYear [2000 .. 2100]
636Long year
8haskell
zjst0
package main import "fmt" func sieve(limit int) []int { var primes []int c := make([]bool, limit + 1)
635Long primes
0go
ey7a6
(loop [[a b & more] (repeatedly #(rand-int 20))] (println a) (when-not (= 10 a) (println b) (recur more)))
640Loops/Break
6clojure
ca89b
<?php echo 'Enter strings (empty string to finish):', PHP_EOL; $output = $previous = readline(); while ($current = readline()) { $p = $previous; $c = $current; while ($p and $c) { $p = substr($p, 1); $c = substr($c, 1); } if (!$p and !$c) { $output .= PHP_EOL . $current; } if ($c) { $output = $previous = $current; } } echo 'Longest string(s) = ', PHP_EOL, $output, PHP_EOL;
632Longest string challenge
12php
vxm2v
$numbers = ; foreach (split(' ', $numbers) as $n) echo , luhnTest($n)? 'valid' : 'not valid', '</br>'; function luhnTest($num) { $len = strlen($num); for ($i = $len-1; $i >= 0; $i--) { $ord = ord($num[$i]); if (($len - 1) & $i) { $sum += $ord; } else { $sum += $ord / 5 + (2 * $ord) % 10; } } return $sum % 10 == 0; }
621Luhn test of credit card numbers
12php
7narp
use strict; use warnings; my $longliteral = join ' ', split ' ', <<END; hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum gold mercury thallium lead bismuth polonium astatine radon francium radium actinium thorium protactinium uranium neptunium plutonium americium curium berkelium californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium flerovium moscovium livermorium tennessine oganesson END my $version = 'Tue Feb 2 22:30:48 UTC 2021'; my $count = my @elements = split ' ', $longliteral; my $last = $elements[-1]; print <<END; version: $version element count: $count last element: $last END
641Long literals, with continuations
2perl
kfmhc
(() => { 'use strict'; const main = () => bagPatterns(5) .join('\n');
638List rooted trees
10javascript
cai9j
import java.time.LocalDate; import java.time.temporal.WeekFields; public class LongYear { public static void main(String[] args) { System.out.printf("Long years this century:%n"); for (int year = 2000 ; year < 2100 ; year++ ) { if ( longYear(year) ) { System.out.print(year + " "); } } } private static boolean longYear(int year) { return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53; } }
636Long year
9java
ou18d
const isLongYear = (year) => { const jan1 = new Date(year, 0, 1); const dec31 = new Date(year, 11, 31); return (4 == jan1.getDay() || 4 == dec31.getDay()) } for (let y = 1995; y <= 2045; y++) { if (isLongYear(y)) { console.log(y) } }
636Long year
10javascript
t7qfm
import Data.List (elemIndex) longPrimesUpTo :: Int -> [Int] longPrimesUpTo n = filter isLongPrime $ takeWhile (< n) primes where sieve (p: xs) = p: sieve [x | x <- xs, x `mod` p /= 0] primes = sieve [2 ..] isLongPrime n = found where cycles = take n (iterate ((`mod` n) . (10 *)) 1) index = elemIndex (head cycles) $ tail cycles found = case index of (Just i) -> n - i == 2 _ -> False display :: Int -> IO () display n = if n <= 64000 then do putStrLn ( show n <> " is " <> show (length $ longPrimesUpTo n) ) display (n * 2) else pure () main :: IO () main = do let fiveHundred = longPrimesUpTo 500 putStrLn ( "The long primes up to 35 are:\n" <> show fiveHundred <> "\n" ) putStrLn ("500 is " <> show (length fiveHundred)) display 1000
635Long primes
8haskell
3h8zj