code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
null | 620Loops/Increment loop index within loop body
| 11kotlin
| bzskb |
while(1) puts(); | 626Loops/Infinite
| 5c
| vq52o |
from itertools import chain
prod, sum_, x, y, z, one,three,seven = 1, 0, 5, -5, -2, 1, 3, 7
def _range(x, y, z=1):
return range(x, y + (1 if z > 0 else -1), z)
print(f'list(_range(x, y, z)) = {list(_range(x, y, z))}')
print(f'list(_range(-seven, seven, x)) = {list(_range(-seven, seven, x))}')
for j in chain(_range(-three, 3**3, three), _range(-seven, seven, x),
_range(555, 550 - y), _range(22, -28, -three),
_range(1927, 1939), _range(x, y, z),
_range(11**x, 11**x + 1)):
sum_ += abs(j)
if abs(prod) < 2**27 and (j != 0):
prod *= j
print(f' sum= {sum_}\nprod= {prod}') | 619Loops/With multiple ranges
| 3python
| p38bm |
(def i (ref 1024))
(while (> @i 0)
(println @i)
(dosync (ref-set i (quot @i 2)))) | 625Loops/While
| 6clojure
| 2x5l1 |
null | 620Loops/Increment loop index within loop body
| 1lua
| p30bw |
package main
import (
"fmt"
"math/big"
)
var primes = []uint{3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127}
var mersennes = []uint{521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689,
9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091,
756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917,
20996011, 24036583}
func main() {
llTest(primes)
fmt.Println()
llTest(mersennes)
}
func llTest(ps []uint) {
var s, m big.Int
one := big.NewInt(1)
two := big.NewInt(2)
for _, p := range ps {
m.Sub(m.Lsh(one, p), one)
s.SetInt64(4)
for i := uint(2); i < p; i++ {
s.Mod(s.Sub(s.Mul(&s, &s), two), &m)
}
if s.BitLen() == 0 {
fmt.Printf("M%d ", p)
}
}
} | 618Lucas-Lehmer test
| 0go
| xctwf |
module Main
where
main = printMersennes $ take 45 $ filter lucasLehmer $ sieve [2..]
s mp 1 = 4 `mod` mp
s mp n = ((s mp $ n-1)^2-2) `mod` mp
lucasLehmer 2 = True
lucasLehmer p = s (2^p-1) (p-1) == 0
printMersennes = mapM_ (\x -> putStrLn $ "M" ++ show x) | 618Lucas-Lehmer test
| 8haskell
| ypg66 |
require 'matrix'
class Matrix
def lu_decomposition
p = get_pivot
tmp = p * self
u = Matrix.zero(row_size).to_a
l = Matrix.identity(row_size).to_a
(0 ... row_size).each do |i|
(0 ... row_size).each do |j|
if j >= i
u[i][j] = tmp[i,j] - (0 ... i).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}
else
l[i][j] = (tmp[i,j] - (0 ... j).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j]
end
end
end
[ Matrix[*l], Matrix[*u], p ]
end
def get_pivot
raise ArgumentError, unless square?
id = Matrix.identity(row_size).to_a
(0 ... row_size).each do |i|
max = self[i,i]
row = i
(i ... row_size).each do |j|
if self[j,i] > max
max = self[j,i]
row = j
end
end
id[i], id[row] = id[row], id[i]
end
Matrix[*id]
end
def pretty_print(format, head=nil)
puts head if head
puts each_slice(column_size).map{|row| format*row_size % row}
end
end
puts
a = Matrix[[1, 3, 5],
[2, 4, 7],
[1, 1, 0]]
a.pretty_print(, )
l, u, p = a.lu_decomposition
l.pretty_print(, )
u.pretty_print(, )
p.pretty_print(, )
puts
a = Matrix[[11, 9,24,2],
[ 1, 5, 2,6],
[ 3,17,18,1],
[ 2, 5, 7,1]]
a.pretty_print(, )
l, u, p = a.lu_decomposition
l.pretty_print(, )
u.pretty_print(, )
p.pretty_print(, ) | 615LU decomposition
| 14ruby
| risgs |
(loop [] (println "SPAM") (recur)) | 626Loops/Infinite
| 6clojure
| rijg2 |
x, y, z, one, three, seven = 5, -5, -2, 1, 3, 7
enums = (-three).step(3**3, three) +
(-seven).step(seven, x) +
555 .step(550-y, -1) +
22 .step(-28, -three) +
(1927..1939) +
x .step(y, z) +
(11**x) .step(11**x + one)
puts
prod = enums.inject(1){|prod, j| ((prod.abs < 2**27) && j!=0)? prod*j: prod}
puts | 619Loops/With multiple ranges
| 14ruby
| ayi1s |
#![allow(non_snake_case)]
use ndarray::{Array, Axis, Array2, arr2, Zip, NdFloat, s};
fn main() {
println!("Example 1:");
let A: Array2<f64> = arr2(&[
[1.0, 3.0, 5.0],
[2.0, 4.0, 7.0],
[1.0, 1.0, 0.0],
]);
println!("A \n {}", A);
let (L, U, P) = lu_decomp(A);
println!("L \n {}", L);
println!("U \n {}", U);
println!("P \n {}", P);
println!("\nExample 2:");
let A: Array2<f64> = arr2(&[
[11.0, 9.0, 24.0, 2.0],
[1.0, 5.0, 2.0, 6.0],
[3.0, 17.0, 18.0, 1.0],
[2.0, 5.0, 7.0, 1.0],
]);
println!("A \n {}", A);
let (L, U, P) = lu_decomp(A);
println!("L \n {}", L);
println!("U \n {}", U);
println!("P \n {}", P);
}
fn pivot<T>(A: &Array2<T>) -> Array2<T>
where T: NdFloat {
let matrix_dimension = A.rows();
let mut P: Array2<T> = Array::eye(matrix_dimension);
for (i, column) in A.axis_iter(Axis(1)).enumerate() { | 615LU decomposition
| 15rust
| 7n0rc |
int i;
for(i = 10; i >= 0; --i)
printf(,i); | 627Loops/Downward for
| 5c
| us5v4 |
def ludic(nmax=100000)
Enumerator.new do |y|
y << 1
ary = *2..nmax
until ary.empty?
y << (n = ary.first)
(0...ary.size).step(n){|i| ary[i] = nil}
ary.compact!
end
end
end
puts , ludic.first(25).to_s
puts , ludic(1000).count
puts , ludic.first(2005).last(6).to_s
ludics = ludic(250).to_a
puts ,
ludics.select{|x| ludics.include?(x+2) and ludics.include?(x+6)}.map{|x| [x, x+2, x+6]}.to_s | 611Ludic numbers
| 14ruby
| 7nnri |
(defn luhn? [cc]
(let [factors (cycle [1 2])
numbers (map #(Character/digit % 10) cc)
sum (reduce + (map #(+ (quot % 10) (mod % 10))
(map * (reverse numbers) factors)))]
(zero? (mod sum 10))))
(doseq [n ["49927398716" "49927398717" "1234567812345678" "1234567812345670"]]
(println (luhn? n))) | 621Luhn test of credit card numbers
| 6clojure
| drmnb |
use ntheory qw(is_prime);
$i = 42;
while ($n < 42) {
if (is_prime($i)) {
$n++;
printf "%2d%21s\n", $n, commatize($i);
$i += $i - 1;
}
$i++;
}
sub commatize {
(my $s = reverse shift) =~ s/(.{3})/$1,/g;
$s =~ s/,$//;
$s = reverse $s;
} | 620Loops/Increment loop index within loop body
| 2perl
| 6bu36 |
const ARRAY_MAX: usize = 25_000;
const LUDIC_MAX: usize = 2100; | 611Ludic numbers
| 15rust
| jdd72 |
import java.math.BigInteger;
public class Mersenne
{
public static boolean isPrime(int p) {
if (p == 2)
return true;
else if (p <= 1 || p % 2 == 0)
return false;
else {
int to = (int)Math.sqrt(p);
for (int i = 3; i <= to; i += 2)
if (p % i == 0)
return false;
return true;
}
}
public static boolean isMersennePrime(int p) {
if (p == 2)
return true;
else {
BigInteger m_p = BigInteger.ONE.shiftLeft(p).subtract(BigInteger.ONE);
BigInteger s = BigInteger.valueOf(4);
for (int i = 3; i <= p; i++)
s = s.multiply(s).subtract(BigInteger.valueOf(2)).mod(m_p);
return s.equals(BigInteger.ZERO);
}
} | 618Lucas-Lehmer test
| 9java
| drln9 |
sub compress {
my $uncompressed = shift;
my $dict_size = 256;
my %dictionary = map {chr $_ => chr $_} 0..$dict_size-1;
my $w = "";
my @result;
foreach my $c (split '', $uncompressed) {
my $wc = $w . $c;
if (exists $dictionary{$wc}) {
$w = $wc;
} else {
push @result, $dictionary{$w};
$dictionary{$wc} = $dict_size;
$dict_size++;
$w = $c;
}
}
if ($w) {
push @result, $dictionary{$w};
}
return @result;
}
sub decompress {
my @compressed = @_;
my $dict_size = 256;
my %dictionary = map {chr $_ => chr $_} 0..$dict_size-1;
my $w = shift @compressed;
my $result = $w;
foreach my $k (@compressed) {
my $entry;
if (exists $dictionary{$k}) {
$entry = $dictionary{$k};
} elsif ($k == $dict_size) {
$entry = $w . substr($w,0,1);
} else {
die "Bad compressed k: $k";
}
$result .= $entry;
$dictionary{$dict_size} = $w . substr($entry,0,1);
$dict_size++;
$w = $entry;
}
return $result;
}
my @compressed = compress('TOBEORNOTTOBEORTOBEORNOT');
print "@compressed\n";
my $decompressed = decompress(@compressed);
print "$decompressed\n"; | 616LZW compression
| 2perl
| m1jyz |
puts
story =
until (line = gets).chomp.empty?
story << line
end
story.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var|
print
story.gsub!(/<
end
puts
puts story | 613Mad Libs
| 14ruby
| i4uoh |
def isPrime(n):
for x in 2, 3:
if not n% x:
return n == x
d = 5
while d * d <= n:
for x in 2, 4:
if not n% d:
return False
d += x
return True
i = 42
n = 0
while n < 42:
if isPrime(i):
n += 1
print('n = {:2} {:20,}'.format(n, i))
i += i - 1
i += 1 | 620Loops/Increment loop index within loop body
| 3python
| yp56q |
int i;
for(i = 1; i < 10; i += 2)
printf(, i); | 628Loops/For with a specified step
| 5c
| gog45 |
object Ludic {
def main(args: Array[String]): Unit = {
println(
s"""|First 25 Ludic Numbers: ${ludic.take(25).mkString(", ")}
|Ludic Numbers <= 1000: ${ludic.takeWhile(_ <= 1000).size}
|2000-2005th Ludic Numbers: ${ludic.slice(1999, 2005).mkString(", ")}
|Triplets <= 250: ${triplets.takeWhile(_._3 <= 250).mkString(", ")}""".stripMargin)
}
def dropByN[T](lst: LazyList[T], len: Int): LazyList[T] = lst.grouped(len).flatMap(_.init).to(LazyList)
def ludic: LazyList[Int] = 1 #:: LazyList.unfold(LazyList.from(2)){case n +: ns => Some((n, dropByN(ns, n)))}
def triplets: LazyList[(Int, Int, Int)] = LazyList.from(1).map(n => (n, n + 2, n + 6)).filter{case (a, b, c) => Seq(a, b, c).forall(ludic.takeWhile(_ <= c).contains)}
} | 611Ludic numbers
| 16scala
| bzzk6 |
null | 618Lucas-Lehmer test
| 10javascript
| 6b438 |
i <- 42
primeCount <- 0
while(primeCount < 42)
{
if(gmp::isprime(i) == 2)
{
primeCount <- primeCount + 1
extraCredit <- format(i, big.mark=",", scientific = FALSE)
cat("Prime count:", paste0(primeCount, ";"), "The prime just found was:", extraCredit, "\n")
i <- i + i
}
i <- i + 1
} | 620Loops/Increment loop index within loop body
| 13r
| tjlfz |
(doseq [x (range 10 -1 -1)] (println x)) | 627Loops/Downward for
| 6clojure
| 7njr0 |
class LZW
{
function compress($unc) {
$i;$c;$wc;
$w = ;
$dictionary = array();
$result = array();
$dictSize = 256;
for ($i = 0; $i < 256; $i += 1) {
$dictionary[chr($i)] = $i;
}
for ($i = 0; $i < strlen($unc); $i++) {
$c = $unc[$i];
$wc = $w.$c;
if (array_key_exists($w.$c, $dictionary)) {
$w = $w.$c;
} else {
array_push($result,$dictionary[$w]);
$dictionary[$wc] = $dictSize++;
$w = (string)$c;
}
}
if ($w !== ) {
array_push($result,$dictionary[$w]);
}
return implode(,$result);
}
function decompress($com) {
$com = explode(,$com);
$i;$w;$k;$result;
$dictionary = array();
$entry = ;
$dictSize = 256;
for ($i = 0; $i < 256; $i++) {
$dictionary[$i] = chr($i);
}
$w = chr($com[0]);
$result = $w;
for ($i = 1; $i < count($com);$i++) {
$k = $com[$i];
if ($dictionary[$k]) {
$entry = $dictionary[$k];
} else {
if ($k === $dictSize) {
$entry = $w.$w[0];
} else {
return null;
}
}
$result .= $entry;
$dictionary[$dictSize++] = $w . $entry[0];
$w = $entry;
}
return $result;
}
}
$str = 'TOBEORNOTTOBEORTOBEORNOT';
$lzw = new LZW();
$com = $lzw->compress($str);
$dec = $lzw->decompress($com);
echo $com . . $dec; | 616LZW compression
| 12php
| emta9 |
extern crate regex;
use regex::Regex;
use std::collections::HashMap;
use std::io;
fn main() {
let mut input_line = String::new();
let mut template = String::new();
println!("Please enter a multi-line story template with <parts> to replace, terminated by a blank line.\n");
loop {
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
if input_line.trim().is_empty() {
break;
}
template.push_str(&input_line);
input_line.clear();
}
let re = Regex::new(r"<[^>]+>").unwrap();
let mut parts: HashMap<_, _> = re
.captures_iter(&template)
.map(|x| (x.get(0).unwrap().as_str().to_string(), "".to_string()))
.collect();
if parts.is_empty() {
println!("No <parts> to replace.\n");
} else {
for (k, v) in parts.iter_mut() {
println!("Please provide a replacement for {}: ", k);
io::stdin()
.read_line(&mut input_line)
.expect("The read line failed.");
*v = input_line.trim().to_string();
println!();
template = template.replace(k, v);
input_line.clear();
}
}
println!("Resulting story:\n\n{}", template);
} | 613Mad Libs
| 15rust
| ng5i4 |
main() {
while(true) {
print("SPAM");
}
} | 626Loops/Infinite
| 18dart
| yp965 |
object MadLibs extends App{
val input = "<name> went for a walk in the park. <he or she>\nfound a <noun>. <name> decided to take it home."
println(input)
println
val todo = "(<[^>]+>)".r
val replacements = todo.findAllIn(input).toSet.map{found: String =>
found -> readLine(s"Enter a $found ")
}.toMap
val output = todo.replaceAllIn(input, found => replacements(found.matched))
println
println(output)
} | 613Mad Libs
| 16scala
| tjrfb |
func printAll(values []int) {
for i, x := range values {
fmt.Printf("Item%d =%d\n", i, x)
}
} | 622Loops/Foreach
| 0go
| 7n1r2 |
null | 618Lucas-Lehmer test
| 11kotlin
| 0v6sf |
require 'prime'
limit = 42
i = 42
n = 0
while n < limit do
if i.prime? then
n += 1
puts .ljust(7) + + ,.rjust(19)
i += i
else
i += 1
end
end | 620Loops/Increment loop index within loop body
| 14ruby
| 9agmz |
int val = 0;
do{
val++;
printf(,val);
}while(val % 6 != 0); | 629Loops/Do-while
| 5c
| 2wclo |
def beatles = ["John", "Paul", "George", "Ringo"]
for(name in beatles) {
println name
} | 622Loops/Foreach
| 7groovy
| usjv9 |
import scala.annotation.tailrec
object LoopIncrementWithinBody extends App {
private val (limit, offset) = (42L, 1)
@tailrec
private def loop(i: Long, n: Int): Unit = {
def isPrime(n: Long) =
n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&
((5 to math.sqrt(n).toInt by 2).par forall (n % _ != 0))
if (n < limit + offset)
if (isPrime(i)) {
printf("n =%-2d %,19d%n".formatLocal(java.util.Locale.GERMANY, n, i))
loop(i + i + 1, n + 1)
} else loop(i + 1, n)
}
loop(limit, offset)
} | 620Loops/Increment loop index within loop body
| 16scala
| vqh2s |
import Control.Monad (forM_)
forM_ collect print | 622Loops/Foreach
| 8haskell
| 8ut0z |
for i in {1..5}
do
for ((j=1; j<=i; j++));
do
echo -n "*"
done
echo
done | 630Loops/For
| 4bash
| ous8a |
(loop [i 0]
(println i)
(when (< i 10)
(recur (+ 2 i))))
(doseq [i (range 0 12 2)]
(println i)) | 628Loops/For with a specified step
| 6clojure
| ktkhs |
def compress(uncompressed):
dict_size = 256
dictionary = dict((chr(i), i) for i in range(dict_size))
w =
result = []
for c in uncompressed:
wc = w + c
if wc in dictionary:
w = wc
else:
result.append(dictionary[w])
dictionary[wc] = dict_size
dict_size += 1
w = c
if w:
result.append(dictionary[w])
return result
def decompress(compressed):
from io import StringIO
dict_size = 256
dictionary = dict((i, chr(i)) for i in range(dict_size))
result = StringIO()
w = chr(compressed.pop(0))
result.write(w)
for k in compressed:
if k in dictionary:
entry = dictionary[k]
elif k == dict_size:
entry = w + w[0]
else:
raise ValueError('Bad compressed k:%s'% k)
result.write(entry)
dictionary[dict_size] = w + entry[0]
dict_size += 1
w = entry
return result.getvalue()
compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
print (compressed)
decompressed = decompress(compressed)
print (decompressed) | 616LZW compression
| 3python
| 9ahmf |
package main
import "fmt"
func main() {
for i := 1; ; i++ {
fmt.Print(i)
if i == 10 {
fmt.Println()
break
}
fmt.Print(", ")
}
} | 624Loops/N plus one half
| 0go
| lw5cw |
for(i in (1..10)) {
print i
if (i == 10) break
print ', '
} | 624Loops/N plus one half
| 7groovy
| 6bc3o |
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
values := make([][]int, 10)
for i := range values {
values[i] = make([]int, 10)
for j := range values[i] {
values[i][j] = rand.Intn(20) + 1
}
}
outerLoop:
for i, row := range values {
fmt.Printf("%3d)", i)
for _, value := range row {
fmt.Printf("%3d", value)
if value == 20 {
break outerLoop
}
}
fmt.Printf("\n")
}
fmt.Printf("\n")
} | 623Loops/Nested
| 0go
| 9aumt |
final random = new Random()
def a = []
(0..<10).each {
def row = []
(0..<10).each {
row << (random.nextInt(20) + 1)
}
a << row
}
a.each { println it }
println ()
Outer:
for (i in (0..<a.size())) {
for (j in (0..<a[i].size())) {
if (a[i][j] == 20){
println ([i:i, j:j])
break Outer
}
}
} | 623Loops/Nested
| 7groovy
| zh9t5 |
Iterable<Type> collect;
...
for(Type i:collect){
System.out.println(i);
} | 622Loops/Foreach
| 9java
| em8a5 |
"alpha beta gamma delta".split(" ").forEach(function (x) {
console.log(x);
}); | 622Loops/Foreach
| 10javascript
| 0vfsz |
(loop [i 0]
(let [i* (inc i)]
(println i*)
(when-not (zero? (mod i* 6))
(recur i*)))) | 629Loops/Do-while
| 6clojure
| g854f |
main :: IO ()
main = forM_ [1 .. 10] $ \n -> do
putStr $ show n
putStr $ if n == 10 then "\n" else ", " | 624Loops/N plus one half
| 8haskell
| 16xps |
import Data.List
breakIncl :: (a -> Bool) -> [a] -> [a]
breakIncl p = uncurry ((. take 1). (++)). break p
taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`) | 623Loops/Nested
| 8haskell
| bzwk2 |
def compress(uncompressed)
dict_size = 256
dictionary = Hash[ Array.new(dict_size) {|i| [i.chr, i.chr]} ]
w =
result = []
for c in uncompressed.split('')
wc = w + c
if dictionary.has_key?(wc)
w = wc
else
result << dictionary[w]
dictionary[wc] = dict_size
dict_size += 1
w = c
end
end
result << dictionary[w] unless w.empty?
result
end
def decompress(compressed)
dict_size = 256
dictionary = Hash[ Array.new(dict_size) {|i| [i.chr, i.chr]} ]
w = result = compressed.shift
for k in compressed
if dictionary.has_key?(k)
entry = dictionary[k]
elsif k == dict_size
entry = w + w[0,1]
else
raise 'Bad compressed k:%s' % k
end
result += entry
dictionary[dict_size] = w + entry[0,1]
dict_size += 1
w = entry
end
result
end
compressed = compress('TOBEORNOTTOBEORTOBEORNOT')
p compressed
decompressed = decompress(compressed)
puts decompressed | 616LZW compression
| 14ruby
| lwbcl |
use std::collections::HashMap;
fn compress(data: &[u8]) -> Vec<u32> { | 616LZW compression
| 15rust
| 2xplt |
null | 622Loops/Foreach
| 11kotlin
| ktwh3 |
use Math::GMP qw/:constant/;
sub is_prime { Math::GMP->new(shift)->probab_prime(12); }
sub is_mersenne_prime {
my $p = shift;
return 1 if $p == 2;
my $mp = 2 ** $p - 1;
my $s = 4;
$s = ($s * $s - 2) % $mp for 3..$p;
$s == 0;
}
foreach my $p (2 .. 43_112_609) {
print "M$p\n" if is_prime($p) && is_mersenne_prime($p);
} | 618Lucas-Lehmer test
| 2perl
| 501u2 |
def compress(tc:String) = { | 616LZW compression
| 16scala
| 50eut |
import java.util.Random;
public class NestedLoopTest {
public static final Random gen = new Random();
public static void main(String[] args) {
int[][] a = new int[10][10];
for (int i = 0; i < a.length; i++)
for (int j = 0; j < a[i].length; j++)
a[i][j] = gen.nextInt(20) + 1;
Outer:for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(" " + a[i][j]);
if (a[i][j] == 20)
break Outer; | 623Loops/Nested
| 9java
| gok4m |
public static void main(String[] args) {
for (int i = 1; ; i++) {
System.out.print(i);
if (i == 10)
break;
System.out.print(", ");
}
System.out.println();
} | 624Loops/N plus one half
| 9java
| 7nbrj |
null | 623Loops/Nested
| 10javascript
| ktehq |
int i, j;
for (i = 1; i <= 5; i++) {
for (j = 1; j <= i; j++)
putchar('*');
puts();
} | 630Loops/For
| 5c
| n48i6 |
function loop_plus_half(start, end) {
var str = '',
i;
for (i = start; i <= end; i += 1) {
str += i;
if (i === end) {
break;
}
str += ', ';
}
return str;
}
alert(loop_plus_half(1, 10)); | 624Loops/N plus one half
| 10javascript
| p3wb7 |
class LZW {
class func compress(_ uncompressed:String) -> [Int] {
var dict = [String: Int]()
for i in 0 ..< 256 {
let s = String(Unicode.Scalar(UInt8(i)))
dict[s] = i
}
var dictSize = 256
var w = ""
var result = [Int]()
for c in uncompressed {
let wc = w + String(c)
if dict[wc]!= nil {
w = wc
} else {
result.append(dict[w]!)
dict[wc] = dictSize
dictSize += 1
w = String(c)
}
}
if w!= "" {
result.append(dict[w]!)
}
return result
}
class func decompress(_ compressed:[Int]) -> String? {
var dict = [Int: String]()
for i in 0 ..< 256 {
dict[i] = String(Unicode.Scalar(UInt8(i)))
}
var dictSize = 256
var w = String(Unicode.Scalar(UInt8(compressed[0])))
var result = w
for k in compressed[1 ..< compressed.count] {
let entry: String
if let x = dict[k] {
entry = x
} else if k == dictSize {
entry = w + String(w[w.startIndex])
} else {
return nil
}
result += entry
dict[dictSize] = w + String(entry[entry.startIndex])
dictSize += 1
w = entry
}
return result
}
}
let comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT")
print(comp)
if let decomp = LZW.decompress(comp) {
print(decomp)
} | 616LZW compression
| 17swift
| cek9t |
import java.util.Random
fun main(args: Array<String>) {
val r = Random()
val a = Array(10) { IntArray(10) { r.nextInt(20) + 1 } }
println("array:")
for (i in a.indices) println("row $i: " + a[i].asList())
println("search:")
Outer@ for (i in a.indices) {
print("row $i: ")
for (j in a[i].indices) {
print(" " + a[i][j])
if (a[i][j] == 20) break@Outer
}
println()
}
println()
} | 623Loops/Nested
| 11kotlin
| 2xgli |
package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
} | 626Loops/Infinite
| 0go
| s28qa |
null | 624Loops/N plus one half
| 11kotlin
| usrvc |
while (true) {
println 'SPAM'
} | 626Loops/Infinite
| 7groovy
| ayw1p |
t={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]="fooday"}
for key, value in pairs(t) do
print(value, key)
end | 622Loops/Foreach
| 1lua
| bzxka |
from sys import stdout
from math import sqrt, log
def is_prime ( p ):
if p == 2: return True
elif p <= 1 or p% 2 == 0: return False
else:
for i in range(3, int(sqrt(p))+1, 2 ):
if p% i == 0: return False
return True
def is_mersenne_prime ( p ):
if p == 2:
return True
else:
m_p = ( 1 << p ) - 1
s = 4
for i in range(3, p+1):
s = (s ** 2 - 2)% m_p
return s == 0
precision = 20000
long_bits_width = precision * log(10, 2)
upb_prime = int( long_bits_width - 1 ) / 2
upb_count = 45
print (%upb_prime)
count=0
for p in range(2, int(upb_prime+1)):
if is_prime(p) and is_mersenne_prime(p):
print(%p),
stdout.flush()
count += 1
if count >= upb_count: break
print | 618Lucas-Lehmer test
| 3python
| 48a5k |
forever (putStrLn "SPAM") | 626Loops/Infinite
| 8haskell
| 9almo |
require(gmp)
n <- 4423
p <- seq(1, n, by = 2)
q <- length(p)
p[1] <- 2
for (k in seq(3, sqrt(n), by = 2))
if (p[(k + 1)/2]!= 0)
p[seq((k * k + 1)/2, q, by = k)] <- 0
p <- p[p > 0]
cat(p[1]," special case M2 == 3\n")
p <- p[-1]
z2 <- gmp::as.bigz(2)
z4 <- z2 * z2
zp <- gmp::as.bigz(p)
zmp <- z2^zp - 1
S <- rep(z4, length(p))
for (i in 1:(p[length(p)] - 2)){
S <- gmp::mod.bigz(S * S - z2, zmp)
if( i+2 == p[1] ){
if( S[1] == 0 ){
cat( p[1], "\n")
flush.console()
}
p <- p[-1]
zmp <- zmp[-1]
S <- S[-1]
}
} | 618Lucas-Lehmer test
| 13r
| 2xklg |
i := 1024
for i > 0 {
fmt.Printf("%d\n", i)
i /= 2
} | 625Loops/While
| 0go
| 16wp5 |
(doseq [i (range 5), j (range (inc i))]
(print "*")
(if (= i j) (println))) | 630Loops/For
| 6clojure
| 3hfzr |
package main
import (
"fmt"
"strings"
)
const input = `49927398716
49927398717
1234567812345678
1234567812345670`
var t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}
func luhn(s string) bool {
odd := len(s) & 1
var sum int
for i, c := range s {
if c < '0' || c > '9' {
return false
}
if i&1 == odd {
sum += t[c-'0']
} else {
sum += int(c - '0')
}
}
return sum%10 == 0
}
func main() {
for _, s := range strings.Split(input, "\n") {
fmt.Println(s, luhn(s))
}
} | 621Luhn test of credit card numbers
| 0go
| ushvt |
int i = 1024
while (i > 0) {
println i
i /= 2
} | 625Loops/While
| 7groovy
| jdb7o |
import Control.Monad (when)
main = loop 1024
where loop n = when (n > 0)
(do print n
loop (n `div` 2)) | 625Loops/While
| 8haskell
| tj6f7 |
def checkLuhn(number) {
int total
(number as String).reverse().eachWithIndex { ch, index ->
def digit = Integer.parseInt(ch)
total += (index % 2 ==0) ? digit: [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][digit]
}
total % 10 == 0
} | 621Luhn test of credit card numbers
| 7groovy
| 9a4m4 |
for i := 10; i >= 0; i-- {
fmt.Println(i)
} | 627Loops/Downward for
| 0go
| 0v8sk |
t = {}
for i = 1, 20 do
t[i] = {}
for j = 1, 20 do t[i][j] = math.random(20) end
end
function exitable()
for i = 1, 20 do
for j = 1, 20 do
if t[i][j] == 20 then
return i, j
end
end
end
end
print(exitable()) | 623Loops/Nested
| 1lua
| vqr2x |
import Data.Char (digitToInt)
luhn = (0 ==) . (`mod` 10) . sum . map (uncurry (+) . (`divMod` 10)) .
zipWith (*) (cycle [1,2]) . map digitToInt . reverse | 621Luhn test of credit card numbers
| 8haskell
| w9ied |
for (i in (10..0)) {
println i
} | 627Loops/Downward for
| 7groovy
| emwal |
for i = 1, 10 do
io.write(i)
if i == 10 then break end
io.write", "
end | 624Loops/N plus one half
| 1lua
| 507u6 |
while (true) {
System.out.println("SPAM");
} | 626Loops/Infinite
| 9java
| tj3f9 |
for (;;) console.log("SPAM"); | 626Loops/Infinite
| 10javascript
| m1cyv |
import Control.Monad
main :: IO ()
main = forM_ [10,9 .. 0] print | 627Loops/Downward for
| 8haskell
| cel94 |
int i = 1024;
while(i > 0){
System.out.println(i);
i >>= 1; | 625Loops/While
| 9java
| 8un06 |
def is_prime ( p )
return true if p == 2
return false if p <= 1 || p.even?
(3 .. Math.sqrt(p)).step(2) do |i|
return false if p % i == 0
end
true
end
def is_mersenne_prime ( p )
return true if p == 2
m_p = ( 1 << p ) - 1
s = 4
(p-2).times { s = (s ** 2 - 2) % m_p }
s == 0
end
precision = 20000
long_bits_width = precision / Math.log(2) * Math.log(10)
upb_prime = (long_bits_width - 1).to_i / 2
upb_count = 45
puts % upb_prime
count = 0
for p in 2..upb_prime
if is_prime(p) && is_mersenne_prime(p)
print % p
count += 1
end
break if count >= upb_count
end
puts | 618Lucas-Lehmer test
| 14ruby
| riwgs |
var n = 1024;
while (n > 0) {
print(n);
n /= 2;
} | 625Loops/While
| 10javascript
| f73dg |
extern crate rug;
extern crate primal;
use rug::Integer;
use rug::ops::Pow;
use std::thread::spawn;
fn is_mersenne (p: usize) {
let p = p as u32;
let mut m = Integer::from(1);
m = m << p;
m = Integer::from(&m - 1);
let mut flag1 = false;
for k in 1..10_000 {
let mut flag2 = false;
let mut div: u32 = 2*k*p + 1;
if &div >= &m {break; }
for j in [3,5,7,11,13,17,19,23,29,31,37].iter() {
if div% j == 0 {
flag2 = true;
break;
}
}
if flag2 == true {continue;}
if div% 8!= 1 && div% 8!= 7 { continue; }
if m.is_divisible_u(div) {
flag1 = true;
break;
}
}
if flag1 == true {return ()}
let mut s = Integer::from(4);
let two = Integer::from(2);
for _i in 2..p {
let mut sqr = s.pow(2);
s = Integer::from(&Integer::from(&sqr & &m) + &Integer::from(&sqr >> p));
if &s >= &m {s = s - &m}
s = Integer::from(&s - &two);
}
if s == 0 {println!("Mersenne: {}",p);}
}
fn main () {
println!("Mersenne: 2");
let limit = 11_214;
let mut thread_handles = vec![];
for p in primal::Primes::all().take_while(|p| *p < limit) {
thread_handles.push(spawn(move || is_mersenne(p)));
}
for handle in thread_handles {
handle.join().unwrap();
}
} | 618Lucas-Lehmer test
| 15rust
| 7nxrc |
null | 626Loops/Infinite
| 11kotlin
| o5n8z |
public class Luhn {
public static void main(String[] args) {
System.out.println(luhnTest("49927398716"));
System.out.println(luhnTest("49927398717"));
System.out.println(luhnTest("1234567812345678"));
System.out.println(luhnTest("1234567812345670"));
}
public static boolean luhnTest(String number){
int s1 = 0, s2 = 0;
String reverse = new StringBuffer(number).reverse().toString();
for(int i = 0 ;i < reverse.length();i++){
int digit = Character.digit(reverse.charAt(i), 10);
if(i % 2 == 0){ | 621Luhn test of credit card numbers
| 9java
| ktxhm |
object LLT extends App {
import Stream._
def primeSieve(s: Stream[Int]): Stream[Int] =
s.head #:: primeSieve(s.tail filter { _ % s.head != 0 })
val primes = primeSieve(from(2))
def mersenne(p: Int): BigInt = (BigInt(2) pow p) - 1
def s(mp: BigInt, p: Int): BigInt = { if (p == 1) 4 else ((s(mp, p - 1) pow 2) - 2) % mp }
val upbPrime = 9941
println(s"Finding Mersenne primes in M[2..$upbPrime]")
((primes takeWhile (_ <= upbPrime)).par map { p => (p, mersenne(p)) }
map { p => if (p._1 == 2) (p, 0) else (p, s(p._2, p._1 - 1)) } filter { _._2 == 0 })
.foreach { p =>
println(s"prime M${(p._1)._1}: " +
{ if ((p._1)._1 < 200) (p._1)._2 else s"(${(p._1)._2.toString.size} digits)" })
}
println("That's All Folks!")
} | 618Lucas-Lehmer test
| 16scala
| kt0hk |
mod10check = function(cc) {
return $A(cc).reverse().map(Number).inject(0, function(s, d, i) {
return s + (i % 2 == 1 ? (d == 9 ? 9 : (d * 2) % 9) : d);
}) % 10 == 0;
};
['49927398716','49927398717','1234567812345678','1234567812345670'].each(function(i){alert(mod10check(i))}); | 621Luhn test of credit card numbers
| 10javascript
| emoao |
null | 625Loops/While
| 11kotlin
| w9sek |
for (int i = 10; i >= 0; i--) {
System.out.println(i);
} | 627Loops/Downward for
| 9java
| zh3tq |
for (var i=10; i>=0; --i) print(i); | 627Loops/Downward for
| 10javascript
| 9acml |
main() {
for (var i = 0; i < 5; i++)
for (var j = 0; j < i + 1; j++)
print("*");
print("\n");
} | 630Loops/For
| 18dart
| qcexo |
null | 627Loops/Downward for
| 11kotlin
| i4no4 |
foreach my $i (@collection) {
print "$i\n";
} | 622Loops/Foreach
| 2perl
| 3klzs |
foreach ($collect as $i) {
echo ;
}
foreach ($collect as $key => $i) {
echo ;
} | 622Loops/Foreach
| 12php
| p3qba |
null | 621Luhn test of credit card numbers
| 11kotlin
| gop4d |
func lucasLehmer(_ p: Int) -> Bool {
let m = BigInt(2).power(p) - 1
var s = BigInt(4)
for _ in 0..<p-2 {
s = ((s * s) - 2)% m
}
return s == 0
}
for prime in Eratosthenes(upTo: 70) where lucasLehmer(prime) {
let m = Int(pow(2, Double(prime))) - 1
print("2^\(prime) - 1 = \(m) is prime")
} | 618Lucas-Lehmer test
| 17swift
| goe49 |
while true do
print("SPAM")
end | 626Loops/Infinite
| 1lua
| i4dot |
for i := 1; i < 10; i += 2 {
fmt.Printf("%d\n", i)
} | 628Loops/For with a specified step
| 0go
| i4iog |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.