code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
import 'dart:math';
String lcsRecursion(String a, String b) {
int aLen = a.length;
int bLen = b.length;
if (aLen == 0 || bLen == 0) {
return "";
} else if (a[aLen-1] == b[bLen-1]) {
return lcsRecursion(a.substring(0,aLen-1),b.substring(0,bLen-1)) + a[aLen-1];
} else {
var x = lcsRecursion(a, b.substring(0,bLen-1));
var y = lcsRecursion(a.substring(0,aLen-1), b);
return (x.length > y.length)? x: y;
}
}
String lcsDynamic(String a, String b) {
var lengths = new List<List<int>>.generate(a.length + 1,
(_) => new List.filled(b.length+1, 0), growable: false); | 637Longest common subsequence
| 18dart
| can9e |
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, ); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, , cnt, c);
cnt = 1;
}
}
}
return 0;
} | 642Look-and-say sequence
| 5c
| 8vr04 |
null | 633Longest common substring
| 11kotlin
| jnu7r |
10.downto(0) do |i|
puts i
end | 627Loops/Downward for
| 14ruby
| hfkjx |
revision =
elements = (
)
def report():
items = elements.split()
print(f)
print(f)
print(f)
if __name__ == :
report() | 641Long literals, with continuations
| 3python
| bt9kr |
null | 638List rooted trees
| 11kotlin
| n41ij |
import java.util.LinkedList;
import java.util.List;
public class LongPrimes
{
private static void sieve(int limit, List<Integer> primes)
{
boolean[] c = new boolean[limit];
for (int i = 0; i < limit; i++)
c[i] = false; | 635Long primes
| 9java
| i5eos |
loop {puts } | 626Loops/Infinite
| 14ruby
| jdk7x |
fn main() {
for i in (0..=10).rev() {
println!("{}", i);
}
} | 627Loops/Downward for
| 15rust
| ktbh5 |
char ch = 'z'; | 643Literals/String
| 5c
| sl5q5 |
elements = %w(
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)
puts | 641Long literals, with continuations
| 14ruby
| 13lpw |
tree_list = {}
offset = {}
function init()
for i=1,32 do
if i == 2 then
table.insert(offset, 1)
else
table.insert(offset, 0)
end
end
end
function append(t)
local v = 1 | (t << 1)
table.insert(tree_list, v)
end
function show(t, l)
while l > 0 do
l = l - 1
if (t % 2) == 1 then
io.write('(')
else
io.write(')')
end
t = t >> 1
end
end
function listTrees(n)
local i = offset[n]
while i < offset[n + 1] do
show(tree_list[i + 1], n * 2)
print()
i = i + 1
end
end
function assemble(m, t, sl, pos, rem)
if rem == 0 then
append(t)
return
end
local pp = pos
local ss = sl
if sl > rem then
ss = rem
pp = offset[ss]
elseif pp >= offset[ss + 1] then
ss = ss - 1
if ss == 0 then
return
end
pp = offset[ss]
end
assemble(n, t << (2 * ss) | tree_list[pp + 1], ss, pp, rem - ss)
assemble(n, t, ss, pp + 1, rem)
end
function makeTrees(n)
if offset[n + 1] ~= 0 then
return
end
if n > 0 then
makeTrees(n - 1)
end
assemble(n, 0, n - 1, offset[n - 1], n - 1)
offset[n + 1] = #tree_list
end
function test(n)
append(0)
makeTrees(n)
print(string.format("Number of%d-trees:%d", n, offset[n+1] - offset[n]))
listTrees(n)
end
init()
test(5) | 638List rooted trees
| 1lua
| dganq |
0.
0.0
.0
1e3
1e-300
6.02E+23 | 639Literals/Floating point
| 0go
| 2wnl7 |
fun main() {
val has53Weeks = { year: Int -> LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53 }
println("Long years this century:")
(2000..2100).filter(has53Weeks)
.forEach { year -> print("$year ")}
} | 636Long year
| 11kotlin
| x9jws |
char a1[] = {'a','b','c'};
char a2[] = {'A','B','C'};
int a3[] = {1,2,3};
int main(void) {
for (int i = 0; i < 3; i++) {
printf(, a1[i], a2[i], a3[i]);
}
} | 644Loop over multiple arrays simultaneously
| 5c
| oug80 |
import fileinput
def longer(a, b):
try:
b[len(a)-1]
return False
except:
return True
longest, lines = '', ''
for x in fileinput.input():
if longer(x, longest):
lines, longest = x, x
elif not longer(longest, x):
lines += x
print(lines, end='') | 632Longest string challenge
| 3python
| slaq9 |
fn main() {
loop {
println!("SPAM");
}
} | 626Loops/Infinite
| 15rust
| hfbj2 |
for(i <- 10 to 0 by -1) println(i) | 627Loops/Downward for
| 16scala
| 16apf |
use strict;
use warnings;
use feature 'say';
sub bagchain {
my($x, $n, $bb, $start) = @_;
return [@$x] unless $n;
my @sets;
$start //= 0;
for my $i ($start .. @$bb-1) {
my($c, $s) = @{$$bb[$i]};
push @sets, bagchain([$$x[0] + $c, $$x[1] . $s], $n-$c, $bb, $i) if $c <= $n
}
@sets
}
sub bags {
my($n) = @_;
return [0, ''] unless $n;
my(@upto,@sets);
push @upto, bags($_) for reverse 1 .. $n-1;
for ( bagchain([0, ''], $n-1, \@upto) ) {
my($c,$s) = @$_;
push @sets, [$c+1, '(' . $s . ')']
}
@sets;
}
sub replace_brackets {
my $bags;
my $depth = 0;
for my $b (split //, $_[0]) {
if ($b eq '(') { $bags .= (qw<( [ {>)[$depth++ % 3] }
else { $bags .= (qw<) ] }>)[--$depth % 3] }
}
$bags
}
say replace_brackets $$_[1] for bags(5); | 638List rooted trees
| 2perl
| 7imrh |
int main(void)
{
printf(,
( (727 == 0x2d7) &&
(727 == 01327) ) ? : );
return 0;
} | 645Literals/Integer
| 5c
| 13ypj |
println 1.00f | 639Literals/Floating point
| 7groovy
| ybs6o |
main = print [0.1,23.3,35e-1,56E+2,14.67e1] | 639Literals/Floating point
| 8haskell
| a6u1g |
null | 635Long primes
| 11kotlin
| qckx1 |
while (true)
println("SPAM") | 626Loops/Infinite
| 16scala
| p3abj |
[\h \e \l \l \o]
\uXXXX
\\ | 643Literals/String
| 6clojure
| n4jik |
user=> 2r1001
9
user=> 8r64
52
user=> 064
52
user=> 16r4b
75
user=> 0x4b
75
user=> | 645Literals/Integer
| 6clojure
| qc2xt |
(defn digits-seq
"Returns a seq of the digits of a number (L->R)."
[n]
(loop [digits (), number n]
(if (zero? number) (seq digits)
(recur (cons (mod number 10) digits)
(quot number 10)))))
(defn join-digits
"Converts a digits-seq back in to a number."
[ds]
(reduce (fn [n d] (+ (* 10 n) d)) ds))
(defn look-and-say [n]
(->> n digits-seq (partition-by identity)
(mapcat (juxt count first)) join-digits)) | 642Look-and-say sequence
| 6clojure
| frbdm |
use strict ;
use warnings ;
sub longestCommonSubstr {
my $first = shift ;
my $second = shift ;
my %firstsubs = findSubstrings ( $first );
my %secondsubs = findSubstrings ( $second ) ;
my @commonsubs ;
foreach my $subst ( keys %firstsubs ) {
if ( exists $secondsubs{ $subst } ) {
push ( @commonsubs , $subst ) ;
}
}
my @sorted = sort { length $b <=> length $a } @commonsubs ;
return $sorted[0] ;
}
sub findSubstrings {
my $string = shift ;
my %substrings ;
my $l = length $string ;
for ( my $start = 0 ; $start < $l ; $start++ ) {
for ( my $howmany = 1 ; $howmany < $l - $start + 1 ; $howmany++) {
$substrings{substr( $string , $start , $howmany) } = 1 ;
}
}
return %substrings ;
}
my $longest = longestCommonSubstr( "thisisatest" ,"testing123testing" ) ;
print "The longest common substring of <thisisatest> and <testing123testing> is $longest!\n" ; | 633Longest common substring
| 2perl
| t78fg |
n = 1024
while n > 0:
print n
n | 625Loops/While
| 3python
| 2x5lz |
void longmulti(const char *a, const char *b, char *c)
{
int i = 0, j = 0, k = 0, n, carry;
int la, lb;
if (!strcmp(a, ) || !strcmp(b, )) {
c[0] = '0', c[1] = '\0';
return;
}
if (a[0] == '-') { i = 1; k = !k; }
if (b[0] == '-') { j = 1; k = !k; }
if (i || j) {
if (k) c[0] = '-';
longmulti(a + i, b + j, c + k);
return;
}
la = strlen(a);
lb = strlen(b);
memset(c, '0', la + lb);
c[la + lb] = '\0';
for (i = la - 1; i >= 0; i--) {
for (j = lb - 1, k = i + j + 1, carry = 0; j >= 0; j--, k--) {
n = I(a[i]) * I(b[j]) + I(c[k]) + carry;
carry = n / 10;
c[k] = (n % 10) + '0';
}
c[k] += carry;
}
if (c[0] == '0') memmove(c, c + 1, la + lb);
return;
}
int main()
{
char c[1024];
longmulti(, , c);
printf(, c);
return 0;
} | 646Long multiplication
| 5c
| t7jf4 |
def bags(n,cache={}):
if not n: return [(0, )]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
return out
def replace_brackets(s):
depth,out = 0,[]
for c in s:
if c == '(':
out.append([depth%3])
depth += 1
else:
depth -= 1
out.append([depth%3])
return .join(out)
for x in bags(5): print(replace_brackets(x[1])) | 638List rooted trees
| 3python
| jn97p |
1. | 639Literals/Floating point
| 9java
| jnm7c |
use strict;
use warnings;
use DateTime;
for my $century (19 .. 21) {
for my $year ($century*100 .. ++$century*100 - 1) {
print "$year " if DateTime->new(year => $year, month => 12, day => 28)->week_number > 52
}
print "\n";
} | 636Long year
| 2perl
| 2wtlf |
BEGIN {
v = [ ]
m = 0
}
n = $_.length
if n == m then
v <<= $_
elsif n > m then
v = [$_]
m = n
end
END {
v.each { |s| puts s }
} | 632Longest string challenge
| 14ruby
| 8vw01 |
use strict;
sub lis {
my @l = map [], 1 .. @_;
push @{$l[0]}, +$_[0];
for my $i (1 .. @_-1) {
for my $j (0 .. $i - 1) {
if ($_[$j] < $_[$i] and @{$l[$i]} < @{$l[$j]} + 1) {
$l[$i] = [ @{$l[$j]} ];
}
}
push @{$l[$i]}, $_[$i];
}
my ($max, $l) = (0, []);
for (@l) {
($max, $l) = (scalar(@$_), $_) if @$_ > $max;
}
return @$l;
}
print join ' ', lis 3, 2, 6, 4, 5, 1;
print join ' ', lis 0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15; | 631Longest increasing subsequence
| 2perl
| pzjb0 |
package main
import "fmt"
func main() {
for i := 1; i <= 10; i++ {
fmt.Printf("%d", i)
if i%5 == 0 {
fmt.Printf("\n")
continue
}
fmt.Printf(", ")
}
} | 634Loops/Continue
| 0go
| slpqa |
for (i in 1..10) {
print i
if (i % 5 == 0) {
println ()
continue
}
print ', '
} | 634Loops/Continue
| 7groovy
| a671p |
i <- 1024L
while(i > 0)
{
print(i)
i <- i%/% 2
} | 625Loops/While
| 13r
| m1ly4 |
package main
import "fmt"
func main() {
for i := 1; i <= 5; i++ {
for j := 1; j <= i; j++ {
fmt.Printf("*")
}
fmt.Printf("\n")
}
} | 630Loops/For
| 0go
| ro5gm |
val d: Double = 1.0
val d2: Double = 1.234e-10
val f: Float = 728832f
val f2: Float = 728832F | 639Literals/Floating point
| 11kotlin
| 5stua |
function isLongYear($year) {
return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}
for ($y=1995; $y<=2045; ++$y) {
if (isLongYear($y)) {
printf(, $y);
}
} | 636Long year
| 12php
| slkqs |
(doseq [s (map #(str %1 %2 %3) "abc" "ABC" "123")]
(println s)) | 644Loop over multiple arrays simultaneously
| 6clojure
| t7kfv |
use std::cmp::Ordering;
use std::io::BufRead; | 632Longest string challenge
| 15rust
| oux83 |
import Control.Monad (forM)
main = forM [1..10] out
where
out x | x `mod` 5 == 0 = print x
| otherwise = (putStr . (++", ") . show) x | 634Loops/Continue
| 8haskell
| 91fmo |
for(i in (1..6)) {
for(j in (1..i)) {
print '*'
}
println ()
} | 630Loops/For
| 7groovy
| vxc28 |
3.14159
314.159E-2 | 639Literals/Floating point
| 1lua
| 40z5c |
use ntheory qw/divisors powmod is_prime/;
sub is_long_prime {
my($p) = @_;
return 0 unless is_prime($p);
for my $d (divisors($p-1)) {
return $d+1 == $p if powmod(10, $d, $p) == 1;
}
0;
}
print "Long primes 500:\n";
print join(' ', grep {is_long_prime($_) } 1 .. 500), "\n\n";
for my $n (500, 1000, 2000, 4000, 8000, 16000, 32000, 64000) {
printf "Number of long primes $n:%d\n", scalar grep { is_long_prime($_) } 1 .. $n;
} | 635Long primes
| 2perl
| vx320 |
val longest = scala.io.Source.fromFile(args.head).getLines.toIterable.groupBy(_.length).max._2
println(longest mkString "\n") | 632Longest string challenge
| 16scala
| dg0ng |
<?php
class Node {
public $val;
public $back = NULL;
}
function lis($n) {
$pileTops = array();
foreach ($n as $x) {
$low = 0; $high = count($pileTops)-1;
while ($low <= $high) {
$mid = (int)(($low + $high) / 2);
if ($pileTops[$mid]->val >= $x)
$high = $mid - 1;
else
$low = $mid + 1;
}
$i = $low;
$node = new Node();
$node->val = $x;
if ($i != 0)
$node->back = $pileTops[$i-1];
$pileTops[$i] = $node;
}
$result = array();
for ($node = count($pileTops)? $pileTops[count($pileTops)-1] : NULL;
$node != NULL; $node = $node->back)
$result[] = $node->val;
return array_reverse($result);
}
print_r(lis(array(3, 2, 6, 4, 5, 1)));
print_r(lis(array(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)));
?> | 631Longest increasing subsequence
| 12php
| ybt61 |
TREE_LIST = []
OFFSET = []
for i in 0..31
if i == 1 then
OFFSET << 1
else
OFFSET << 0
end
end
def append(t)
TREE_LIST << (1 | (t << 1))
end
def show(t, l)
while l > 0
l = l - 1
if t % 2 == 1 then
print '('
else
print ')'
end
t = t >> 1
end
end
def listTrees(n)
for i in OFFSET[n] .. OFFSET[n + 1] - 1
show(TREE_LIST[i], n * 2)
print
end
end
def assemble(n, t, sl, pos, rem)
if rem == 0 then
append(t)
return
end
if sl > rem then
sl = rem
pos = OFFSET[sl]
elsif pos >= OFFSET[sl + 1] then
sl = sl - 1
if sl == 0 then
return
end
pos = OFFSET[sl]
end
assemble(n, t << (2 * sl) | TREE_LIST[pos], sl, pos, rem - sl)
assemble(n, t, sl, pos + 1, rem)
end
def makeTrees(n)
if OFFSET[n + 1]!= 0 then
return
end
if n > 0 then
makeTrees(n - 1)
end
assemble(n, 0, n - 1, OFFSET[n - 1], n - 1)
OFFSET[n + 1] = TREE_LIST.length()
end
def test(n)
if n < 1 || n > 12 then
raise ArgumentError.new()
end
append(0)
makeTrees(n)
print % [n, OFFSET[n + 1] - OFFSET[n]]
listTrees(n)
end
test(5) | 638List rooted trees
| 14ruby
| kflhg |
void print_logic(int a, int b)
{
printf(, a && b);
printf(, a || b);
printf(, !a);
} | 647Logical operations
| 5c
| 2wwlo |
'''Long Year?'''
from datetime import date
def longYear(y):
'''True if the ISO year y has 53 weeks.'''
return 52 < date(y, 12, 28).isocalendar()[1]
def main():
'''Longer (53 week) years in the range 2000-2100'''
for year in [
x for x in range(2000, 1 + 2100)
if longYear(x)
]:
print(year)
if __name__ == '__main__':
main() | 636Long year
| 3python
| vxz29 |
func lcs(a, b string) string {
aLen := len(a)
bLen := len(b)
if aLen == 0 || bLen == 0 {
return ""
} else if a[aLen-1] == b[bLen-1] {
return lcs(a[:aLen-1], b[:bLen-1]) + string(a[aLen-1])
}
x := lcs(a, b[:bLen-1])
y := lcs(a[:aLen-1], b)
if len(x) > len(y) {
return x
}
return y
} | 637Longest common subsequence
| 0go
| oup8q |
def lcs(xstr, ystr) {
if (xstr == "" || ystr == "") {
return "";
}
def x = xstr[0];
def y = ystr[0];
def xs = xstr.size() > 1 ? xstr[1..-1]: "";
def ys = ystr.size() > 1 ? ystr[1..-1]: "";
if (x == y) {
return (x + lcs(xs, ys));
}
def lcs1 = lcs(xstr, ys);
def lcs2 = lcs(xs, ystr);
lcs1.size() > lcs2.size() ? lcs1: lcs2;
}
println(lcs("1234", "1224533324"));
println(lcs("thisisatest", "testing123testing")); | 637Longest common subsequence
| 7groovy
| x97wl |
for(int i = 1;i <= 10; i++){
System.out.print(i);
if(i % 5 == 0){
System.out.println();
continue;
}
System.out.print(", ");
} | 634Loops/Continue
| 9java
| t70f9 |
s1 =
s2 =
len1, len2 = len(s1), len(s2)
ir, jr = 0, -1
for i1 in range(len1):
i2 = s2.find(s1[i1])
while i2 >= 0:
j1, j2 = i1, i2
while j1 < len1 and j2 < len2 and s2[j2] == s1[j1]:
if j1-i1 >= jr-ir:
ir, jr = i1, j1
j1 += 1; j2 += 1
i2 = s2.find(s1[i1], i2+1)
print (s1[ir:jr+1]) | 633Longest common substring
| 3python
| zjott |
>>> def luhn(n):
r = [int(ch) for ch in str(n)][::-1]
return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2]))% 10 == 0
>>> for n in (49927398716, 49927398717, 1234567812345678, 1234567812345670):
print(n, luhn(n)) | 621Luhn test of credit card numbers
| 3python
| drmn1 |
i = 1024
while i > 0 do
puts i
i /= 2
end | 625Loops/While
| 14ruby
| usgvz |
my $val = 0;
do {
$val++;
print "$val\n";
} while ($val % 6); | 629Loops/Do-while
| 2perl
| 40u5d |
import Control.Monad
main = do
forM_ [1..5] $ \i -> do
forM_ [1..i] $ \j -> do
putChar '*'
putChar '\n' | 630Loops/For
| 8haskell
| 02xs7 |
(defn logical [a b]
(prn (str "a and b is " (and a b)))
(prn (str "a or b is " (or a b)))
(prn (str "not a is " (not a))))
(logical true false) | 647Logical operations
| 6clojure
| g884f |
require 'date'
def long_year?(year = Date.today.year)
Date.new(year, 12, 28).cweek == 53
end
(2020..2030).each{|year| puts } | 636Long year
| 14ruby
| 5s6uj |
extern crate time; | 636Long year
| 15rust
| 40y5u |
longest xs ys = if length xs > length ys then xs else ys
lcs [] _ = []
lcs _ [] = []
lcs (x:xs) (y:ys)
| x == y = x: lcs xs ys
| otherwise = longest (lcs (x:xs) ys) (lcs xs (y:ys)) | 637Longest common subsequence
| 8haskell
| 2wfll |
var output = "";
for (var i = 1; i <= 10; i++) {
output += i;
if (i % 5 == 0) {
print(output);
output = "";
continue;
}
output += ", ";
} | 634Loops/Continue
| 10javascript
| mpdyv |
while true {
println("SPAM")
} | 626Loops/Infinite
| 17swift
| 7nhrq |
fn main() {
let mut n: i32 = 1024;
while n > 0 {
println!("{}", n);
n /= 2;
}
} | 625Loops/While
| 15rust
| 50ruq |
for i in stride(from: 10, through: 0, by: -1) {
println(i)
} | 627Loops/Downward for
| 17swift
| jdh74 |
import java.time.temporal.TemporalAdjusters.firstInMonth
import java.time.temporal.{ChronoField, IsoFields}
import java.time.{DayOfWeek, LocalDate, Month}
import scala.util.{Failure, Try}
private object LongYear extends App {
private val (currentCentury, maxWeekNumber) = (LocalDate.now().getYear / 100, ChronoField.ALIGNED_WEEK_OF_YEAR.range().getMaximum)
private val centuries = currentCentury * 100 until (currentCentury + 1) * 100
private val results = List(
centuries.filter(isThursdayFirstOrLast),
centuries.filter(year => maxIsoWeeks(year) == maxWeekNumber),
centuries.filter(mostThursdaysInYear)
) | 636Long year
| 16scala
| 7icr9 |
$val = 0;
do {
$val++;
print ;
} while ($val % 6 != 0); | 629Loops/Do-while
| 12php
| i58ov |
.5;
0.5;
1.23345e10;
1.23445e-10;
100_000_000; | 639Literals/Floating point
| 2perl
| ouk8x |
.12
0.1234
1.2e3
7E-10 | 639Literals/Floating point
| 12php
| g8342 |
def sieve(limit):
primes = []
c = [False] * (limit + 1)
p = 3
while True:
p2 = p * p
if p2 > limit: break
for i in range(p2, limit, 2 * p): c[i] = True
while True:
p += 2
if not c[p]: break
for i in range(3, limit, 2):
if not c[i]: primes.append(i)
return primes
def findPeriod(n):
r = 1
for i in range(1, n): r = (10 * r)% n
rr = r
period = 0
while True:
r = (10 * r)% n
period += 1
if r == rr: break
return period
primes = sieve(64000)
longPrimes = []
for prime in primes:
if findPeriod(prime) == prime - 1:
longPrimes.append(prime)
numbers = [500, 1000, 2000, 4000, 8000, 16000, 32000, 64000]
count = 0
index = 0
totals = [0] * len(numbers)
for longPrime in longPrimes:
if longPrime > numbers[index]:
totals[index] = count
index += 1
count += 1
totals[-1] = count
print('The long primes up to 500 are:')
print(str(longPrimes[:totals[0]]).replace(',', ''))
print('\nThe number of long primes up to:')
for (i, total) in enumerate(totals):
print(' %5d is%d'% (numbers[i], total)) | 635Long primes
| 3python
| uq6vd |
def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return S[::-1]
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]]:
print('a L.I.S. of%s is%s'% (d, longest_increasing_subsequence(d))) | 631Longest increasing subsequence
| 3python
| 13hpc |
null | 634Loops/Continue
| 11kotlin
| oue8z |
is.luhn <- function(cc){
numbers <- as.numeric(rev(unlist(strsplit(cc,""))))
(sum(numbers[seq(1,length(numbers),by=2)]) + sum({numbers[seq(2,length(numbers),by=2)]*2 ->.; .%%10 +.%/%10})) %% 10 == 0
}
sapply(c("49927398716","49927398717","1234567812345678","1234567812345670"),is.luhn) | 621Luhn test of credit card numbers
| 13r
| 8uz0x |
var i = 1024
while (i > 0) {
println(i)
i /= 2
} | 625Loops/While
| 16scala
| rihgn |
func isLongYear(_ year: Int) -> Bool {
let year1 = year - 1
let p = (year + (year / 4) - (year / 100) + (year / 400))% 7
let p1 = (year1 + (year1 / 4) - (year1 / 100) + (year1 / 400))% 7
return p == 4 || p1 == 3
}
for range in [1900...1999, 2000...2099, 2100...2199] {
print("\(range): \(range.filter(isLongYear))")
} | 636Long year
| 17swift
| uq3vg |
public static String lcs(String a, String b){
int aLen = a.length();
int bLen = b.length();
if(aLen == 0 || bLen == 0){
return "";
}else if(a.charAt(aLen-1) == b.charAt(bLen-1)){
return lcs(a.substring(0,aLen-1),b.substring(0,bLen-1))
+ a.charAt(aLen-1);
}else{
String x = lcs(a, b.substring(0,bLen-1));
String y = lcs(a.substring(0,aLen-1), b);
return (x.length() > y.length()) ? x : y;
}
} | 637Longest common subsequence
| 9java
| 6k03z |
def longest_common_substring(a,b)
lengths = Array.new(a.length){Array.new(b.length, 0)}
greatestLength = 0
output =
a.each_char.with_index do |x,i|
b.each_char.with_index do |y,j|
next if x!= y
lengths[i][j] = (i.zero? || j.zero?)? 1: lengths[i-1][j-1] + 1
if lengths[i][j] > greatestLength
greatestLength = lengths[i][j]
output = a[i - greatestLength + 1, greatestLength]
end
end
end
output
end
p longest_common_substring(, ) | 633Longest common substring
| 14ruby
| 6kn3t |
FLOAT
: '.' DIGITS (Exponent)?
| DIGITS '.' Exponent
| DIGITS ('.' (DIGITS (Exponent)?)? | Exponent)
;
DIGITS: ( '0' .. '9' )+;
Exponent
: ('e' | 'E') ( '+' | '-' )? DIGITS
; | 639Literals/Floating point
| 3python
| i5bof |
const isLongYear = (year: number): boolean => {
const jan1: Date = new Date(year, 0, 1);
const dec31: Date = new Date(year, 11, 31);
return (4 == jan1.getDay() || 4 == dec31.getDay())
}
for (let y: number = 1995; y <= 2045; y++) {
if (isLongYear(y)) {
console.log(y)
}
} | 636Long year
| 20typescript
| wm7eu |
function lcs(a, b) {
var aSub = a.substr(0, a.length - 1);
var bSub = b.substr(0, b.length - 1);
if (a.length === 0 || b.length === 0) {
return '';
} else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) {
return lcs(aSub, bSub) + a.charAt(a.length - 1);
} else {
var x = lcs(a, bSub);
var y = lcs(aSub, b);
return (x.length > y.length) ? x : y;
}
} | 637Longest common subsequence
| 10javascript
| ledcf |
fn longest_common_substring(s1: &str, s2: &str) -> String {
let s1_chars: Vec<char> = s1.chars().collect();
let s2_chars: Vec<char> = s2.chars().collect();
let mut lcs = "".to_string();
for i in 0..s1_chars.len() {
for j in 0..s2_chars.len() {
if s1_chars[i] == s2_chars[j] {
let mut tmp_lcs = s2_chars[j].to_string();
let mut tmp_i = i + 1;
let mut tmp_j = j + 1;
while tmp_i < s1_chars.len() && tmp_j < s2_chars.len() && s1_chars[tmp_i] == s2_chars[tmp_j] {
tmp_lcs = format!("{}{}", tmp_lcs, s1_chars[tmp_i]);
tmp_i += 1;
tmp_j += 1;
}
if tmp_lcs.len() > lcs.len() {
lcs = tmp_lcs;
}
}
}
}
lcs
}
fn main() {
let s1 = "thisisatest";
let s2 = "testing123testing";
let lcs = longest_common_substring(s1, s2);
println!("{}", lcs);
} | 633Longest common substring
| 15rust
| ybd68 |
def longestCommonSubstringsOptimizedPureFP(left: String, right: String): Option[Set[String]] =
if (left.nonEmpty && right.nonEmpty) {
val (shorter, longer) =
if (left.length < right.length) (left, right)
else (right, left)
@scala.annotation.tailrec
def recursive(
indexLonger: Int = 0,
indexShorter: Int = 0,
currentLongestLength: Int = 0,
lengthsPrior: List[Int] = List.fill(shorter.length)(0),
lengths: List[Int] = Nil,
accumulator: List[Int] = Nil
): (Int, List[Int]) =
if (indexLonger < longer.length) {
val length =
if (longer(indexLonger) != shorter(indexShorter)) 0
else lengthsPrior.head + 1
val newCurrentLongestLength =
if (length > currentLongestLength) length
else currentLongestLength
val newAccumulator =
if ((length < currentLongestLength) || (length == 0)) accumulator
else {
val entry = indexShorter - length + 1
if (length > currentLongestLength) List(entry)
else entry :: accumulator
}
if (indexShorter < shorter.length - 1)
recursive(
indexLonger,
indexShorter + 1,
newCurrentLongestLength,
lengthsPrior.tail,
length :: lengths,
newAccumulator
)
else
recursive(
indexLonger + 1,
0,
newCurrentLongestLength,
0 :: lengths.reverse,
Nil,
newAccumulator
)
}
else (currentLongestLength, accumulator)
val (length, indexShorters) = recursive()
if (indexShorters.nonEmpty)
Some(
indexShorters
.map {
indexShorter =>
shorter.substring(indexShorter, indexShorter + length)
}
.toSet
)
else None
}
else None
println(longestCommonSubstringsOptimizedPureFP("thisisatest", "testing123testing")) | 633Longest common substring
| 16scala
| caz93 |
2.3
3.
2f64
1_000.2_f32 | 639Literals/Floating point
| 14ruby
| dg1ns |
package main
import "fmt"
import "math/rand"
import "time"
func main() {
rand.Seed(time.Now().UnixNano())
for {
a := rand.Intn(20)
fmt.Println(a)
if a == 10 {
break
}
b := rand.Intn(20)
fmt.Println(b)
}
} | 640Loops/Break
| 0go
| btckh |
func lComSubStr<
S0: Sliceable, S1: Sliceable, T: Equatable where
S0.Generator.Element == T, S1.Generator.Element == T,
S0.Index.Distance == Int, S1.Index.Distance == Int
>(w1: S0, _ w2: S1) -> S0.SubSlice {
var (len, end) = (0, 0)
let empty = Array(Repeat(count: w2.count + 1, repeatedValue: 0))
var mat: [[Int]] = Array(Repeat(count: w1.count + 1, repeatedValue: empty))
for (i, sLett) in w1.enumerate() {
for (j, tLett) in w2.enumerate() where tLett == sLett {
let curLen = mat[i][j] + 1
mat[i + 1][j + 1] = curLen
if curLen > len {
len = curLen
end = i
}
}
}
return w1[advance(w1.startIndex, (end + 1) - len)...advance(w1.startIndex, end)]
}
func lComSubStr(w1: String, _ w2: String) -> String {
return String(lComSubStr(w1.characters, w2.characters))
} | 633Longest common substring
| 17swift
| 3hiz2 |
ch := 'z'
ch = 122 | 643Literals/String
| 0go
| vx82m |
2.3 | 639Literals/Floating point
| 15rust
| frad6 |
1. | 639Literals/Floating point
| 16scala
| 3hxzy |
System: I7-6700HQ, 3.5 GHz, Linux Kernel 5.6.17
Run as: $ ruby longprimes.rb | 635Long primes
| 14ruby
| 40m5p |
null | 635Long primes
| 15rust
| g894o |
final random = new Random()
while (true) {
def random1 = random.nextInt(20)
print random1
if (random1 == 10) break
print ' '
println random.nextInt(20)
} | 640Loops/Break
| 7groovy
| ro3gh |
for i = 1, 10 do
io.write( i )
if i % 5 == 0 then
io.write( "\n" )
else
io.write( ", " )
end
end | 634Loops/Continue
| 1lua
| i5wot |
val = 0
while True:
val +=1
print val
if val% 6 == 0: break | 629Loops/Do-while
| 3python
| g854h |
def string = 'Able was I' | 643Literals/String
| 7groovy
| mpwy5 |
"abcdef" == "abc\
\def"
"abc\ndef" == "abc\n\
\def" | 643Literals/String
| 8haskell
| eylai |
object LongPrimes extends App {
def primeStream = LazyList.from(3, 2)
.filter(p => (3 to math.sqrt(p).ceil.toInt by 2).forall(p % _ > 0))
def longPeriod(p: Int): Boolean = {
val mstart = 10 % p
@annotation.tailrec
def iter(mod: Int, period: Int): Int = {
val mod1 = (10 * mod) % p
if (mod1 == mstart) period
else iter(mod1, period + 1)
}
iter(mstart, 1) == p - 1
}
val longPrimes = primeStream.filter(longPeriod(_))
println("long primes up to 500:")
println(longPrimes.takeWhile(_ <= 500).mkString(" "))
println
val limitList = Seq.tabulate(8)(math.pow(2, _).toInt * 500)
for (limit <- limitList) {
val count = longPrimes.takeWhile(_ <= limit).length
println(f"there are $count%4d long primes up to $limit%5d")
}
} | 635Long primes
| 16scala
| jn27i |
null | 637Longest common subsequence
| 11kotlin
| dgenz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.