code stringlengths 1 46.1k ⌀ | label class label 1.18k
classes | domain_label class label 21
classes | index stringlengths 4 5 |
|---|---|---|---|
package main
import "fmt"
func main() {
sieve(1e6)
if !search(6, 1e6, "left", func(n, pot int) int { return n % pot }) {
panic("997?")
}
if !search(6, 1e6, "right", func(n, _ int) int { return n / 10 }) {
panic("7393?")
}
}
var c []bool
func sieve(ss int) {
c = make([]bool, s... | 102Truncatable primes | 0go | 5l4ul |
package main
import (
"flag"
"fmt"
"math"
"runtime"
"sort"
) | 107Total circles area | 0go | q11xz |
sub truth_table {
my $s = shift;
my (%seen, @vars);
for ($s =~ /([a-zA-Z_]\w*)/g) {
$seen{$_} //= do { push @vars, $_; 1 };
}
print "\n", join("\t", @vars, $s), "\n", '-' x 40, "\n";
@vars = map("\$$_", @vars);
$s =~ s/([a-zA-Z_]\w*)/\$$1/g;
$s = "print(".join(',"\t", ', map("(... | 98Truth table | 2perl | 75prh |
import Data.Numbers.Primes(primes, isPrime)
import Data.List
import Control.Arrow
primes1e6 = reverse. filter (notElem '0'. show) $ takeWhile(<=1000000) primes
rightT, leftT :: Int -> Bool
rightT = all isPrime. takeWhile(>0). drop 1. iterate (`div`10)
leftT x = all isPrime. takeWhile(<x).map (x`mod`) $ iterate (*10) ... | 102Truncatable primes | 8haskell | x1qw4 |
uint64_t modpow(uint64_t a, uint64_t b, uint64_t n) {
uint64_t x = 1, y = a;
while (b > 0) {
if (b % 2 == 1) {
x = (x * y) % n;
}
y = (y * y) % n;
b /= 2;
}
return x % n;
}
struct Solution {
uint64_t root1, root2;
bool exists;
};
struct Solution ma... | 109Tonelli-Shanks algorithm | 5c | wbhec |
data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }
isInside :: Double -> Double -> Circle -> Bool
isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)
isInsideAny :: Double -> Double -> [Circle] -> Bool
isInsideAny x y = any (isInside x y)
approximatedArea :: [Circle] -> Int -> Double
approx... | 107Total circles area | 8haskell | mttyf |
char input[] =
;
typedef struct item_t item_t, *item;
struct item_t { const char *name; int *deps, n_deps, idx, depth; };
int get_item(item *list, int *len, const char *name)
{
int i;
item lst = *list;
for (i = 0; i < *len; i++)
if (!strcmp(lst[i].name, name)) return i;
lst = ... | 110Topological sort | 5c | c3f9c |
public class Topswops {
static final int maxBest = 32;
static int[] best;
static private void trySwaps(int[] deck, int f, int d, int n) {
if (d > best[n])
best[n] = d;
for (int i = n - 1; i >= 0; i--) {
if (deck[i] == -1 || deck[i] == i)
break;
... | 104Topswops | 9java | p7kb3 |
int main() {
double pi = 4 * atan(1);
double radians = pi / 4;
double degrees = 45.0;
double temp;
printf(, sin(radians), sin(degrees * pi / 180));
printf(, cos(radians), cos(degrees * pi / 180));
printf(, tan(radians), tan(degrees * pi / 180));
temp = asin(sin(radians));
printf(, temp,... | 111Trigonometric functions | 5c | l6fcy |
constraints = [
->(st) { st.size == 12 },
->(st) { st.last(6).count(true) == 3 },
->(st) { st.each_slice(2).map(&:last).count(true) == 2 },
->(st) { st[4]? (st[5] & st[6]): true },
->(st) { st[1..3].none? },
->(st) { st.each_slice(2).map(&:first).count(true) == 4 },
->(st) { st[1] ^ st[2] },
->(st) { s... | 100Twelve statements | 14ruby | 2m5lw |
class LogicPuzzle {
val s = new Array[Boolean](13)
var count = 0
def check2: Boolean = {
var count = 0
for (k <- 7 to 12) if (s(k)) count += 1
s(2) == (count == 3)
}
def check3: Boolean = {
var count = 0
for (k <- 2 to 12 by 2) if (s(k)) count += 1
s(3) == (count == 2)
}
def c... | 100Twelve statements | 16scala | 42750 |
from __future__ import print_function, division
from math import sqrt
def cell(n, x, y, start=1):
d, y, x = 0, y - n
l = 2*max(abs(x), abs(y))
d = (l*3 + x + y) if y >= x else (l - x - y)
return (l - 1)**2 + d + start - 1
def show_spiral(n, symbol='
top = start + n*n + 1
is_prime = [False,Fals... | 97Ulam spiral (for primes) | 3python | hgejw |
(defn find-first
" Finds first element of collection that satisifies predicate function pred "
[pred coll]
(first (filter pred coll)))
(defn modpow
" b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and
calculation simplications when g... | 109Tonelli-Shanks algorithm | 6clojure | 8wa05 |
public class CirclesTotalArea {
private static double distSq(double x1, double y1, double x2, double y2) {
return (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
}
private static boolean rectangleFullyInsideCircle(double[] rect, double[] circ) {
double r2 = circ[2] * circ[2]; | 107Total circles area | 9java | f88dv |
null | 104Topswops | 11kotlin | 7ugr4 |
package main
import (
"fmt"
"log"
"math"
)
func main() { | 106Trabb Pardo–Knuth algorithm | 0go | h4gjq |
require(numbers);
plotulamspirR <- function(n, clr, fn, ttl, psz=600) {
cat(" *** START:", date(), "n=",n, "clr=",clr, "psz=", psz, "\n");
if (n%%2==0) {n=n+1}; n2=n*n;
x=y=floor(n/2); xmx=ymx=cnt=1; dir="R";
ttl= paste(c(ttl, n,"x",n," matrix."), sep="", collapse="");
cat(" ***", ttl, "\n");
M <- matrix(c(... | 97Ulam spiral (for primes) | 13r | gvb47 |
import java.util.BitSet;
public class Main {
public static void main(String[] args){
final int MAX = 1000000; | 102Truncatable primes | 9java | b7pk3 |
typedef char* Str;
unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );
int main() {
char s[] = STR_DEMO;
unsigned int i, q;
Str *list = Tokenize( s, SEP, ESC, &q );
if( list != NULL ) {
printf( , STR_DEMO );
printf... | 112Tokenize a string with escaping | 5c | ziqtx |
(use 'clojure.set)
(use 'clojure.contrib.seq-utils)
(defn dep
"Constructs a single-key dependence, represented as a map from
item to a set of items, ensuring that item is not in the set."
[item items]
{item (difference (set items) (list item))})
(defn empty-dep
"Constructs a single-key dependence from item... | 110Topological sort | 6clojure | 5cyuz |
package turing
type Symbol byte
type Motion byte
const (
Left Motion = 'L'
Right Motion = 'R'
Stay Motion = 'N'
)
type Tape struct {
data []Symbol
pos, left int
blank Symbol
} | 103Universal Turing machine | 0go | v9v2m |
null | 104Topswops | 1lua | j5r71 |
(ns user
(:require [clojure.contrib.generic.math-functions :as generic]))
(def pi (* 4 (atan 1)))
(def dtor (/ pi 180))
(def rtod (/ 180 pi))
(def radians (/ pi 4))
(def degrees 45)
(println (str (sin radians) " " (sin (* degrees dtor))))
(println (str (cos radians) " " (cos (* degrees dtor))))
(println (str (tan ... | 111Trigonometric functions | 6clojure | 4ly5o |
import Control.Monad (replicateM, mapM_)
f :: Floating a => a -> a
f x = sqrt (abs x) + 5 * x ** 3
main :: IO ()
main = do
putStrLn "Enter 11 numbers for evaluation"
x <- replicateM 11 readLn
mapM_
((\x ->
if x > 400
then putStrLn "OVERFLOW"
else print x) .
f) $
rever... | 106Trabb Pardo–Knuth algorithm | 8haskell | iqsor |
from itertools import product
while True:
bexp = input('\nBoolean expression: ')
bexp = bexp.strip()
if not bexp:
print()
break
code = compile(bexp, '<string>', 'eval')
names = code.co_names
print('\n' + ' '.join(names), ':', bexp)
for values in product(range(2), repeat=len(... | 98Truth table | 3python | j417p |
null | 107Total circles area | 11kotlin | 8ww0q |
data Move = MLeft | MRight | Stay deriving (Show, Eq)
data Tape a = Tape a [a] [a]
data Action state val = Action val Move state deriving (Show)
instance (Show a) => Show (Tape a) where
show (Tape x lts rts) = concat $ left ++ [hd] ++ right
where hd = "[" ++ show x ++ "]"
... | 103Universal Turing machine | 8haskell | ebeai |
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try {... | 106Trabb Pardo–Knuth algorithm | 9java | xp1wy |
truth_table <- function(x) {
vars <- unique(unlist(strsplit(x, "[^a-zA-Z]+")))
vars <- vars[vars!= ""]
perm <- expand.grid(rep(list(c(FALSE, TRUE)), length(vars)))
names(perm) <- vars
perm[ , x] <- with(perm, eval(parse(text = x)))
perm
}
"%^%" <- xor
truth_table("!A")
truth_table("A | B")
tr... | 98Truth table | 13r | 42h5y |
null | 102Truncatable primes | 11kotlin | ru7go |
typedef struct node_s
{
int value;
struct node_s* left;
struct node_s* right;
} *node;
node tree(int v, node l, node r)
{
node n = malloc(sizeof(struct node_s));
n->value = v;
n->left = l;
n->right = r;
return n;
}
void destroy_tree(node n)
{
if (n->left)
destroy_tree(n->left);
if (n->right)
... | 113Tree traversal | 5c | 6ds32 |
int main(int argc, char *argv[]){
char sequence[256+1] = ;
char inverse[256+1] = ;
char buffer[256+1];
int i;
for(i = 0; i < 8; i++){
strcpy(buffer, sequence);
strcat(sequence, inverse);
strcat(inverse, buffer);
}
puts(sequence);
return 0;
} | 114Thue-Morse | 5c | l6icy |
package main
import "fmt" | 109Tonelli-Shanks algorithm | 0go | c3t9g |
sub next_swop {
my( $max, $level, $p, $d ) = @_;
my $swopped = 0;
for( 2..@$p ){
my @now = @$p;
if( $_ == $now[$_-1] ) {
splice @now, 0, 0, reverse splice @now, 0, $_;
$swopped = 1;
next_swop( $max, $level+1, \@now, [ @$d ] );
}
}
for( 1..@$d ) {
my @now = @$p;
my $next... | 104Topswops | 2perl | f8nd7 |
#!/usr/bin/env js
function main() {
var nums = getNumbers(11);
nums.reverse();
for (var i in nums) {
pardoKnuth(nums[i], fn, 400);
}
}
function pardoKnuth(n, f, max) {
var res = f(n);
putstr('f(' + String(n) + ')');
if (res > max) {
print(' is too large');
} else {
... | 106Trabb Pardo–Knuth algorithm | 10javascript | oxq86 |
max_number = 1000000
numbers = {}
for i = 2, max_number do
numbers[i] = i;
end
for i = 2, max_number do
for j = i+1, max_number do
if numbers[j] ~= 0 and j % i == 0 then numbers[j] = 0 end
end
end
max_prime_left, max_prime_right = 2, 2
for i = 2, max_number do
if numbers[i] ~= 0 then
... | 102Truncatable primes | 1lua | 75jru |
import Data.List (genericTake, genericLength)
import Data.Bits (shiftR)
powMod :: Integer -> Integer -> Integer -> Integer
powMod m b e = go b e 1
where
go b e r
| e == 0 = r
| odd e = go ((b*b) `mod` m) (e `div` 2) ((r*b) `mod` m)
| even e = go ((b*b) `mod` m) (e `div` 2) r
legendre :: Inte... | 109Tonelli-Shanks algorithm | 8haskell | p7gbt |
use strict;
use warnings;
use feature 'say';
use List::AllUtils <min max>;
my @circles = (
[ 1.6417233788, 1.6121789534, 0.0848270516],
[-1.4944608174, 1.2077959613, 1.1039549836],
[ 0.6110294452, -0.6907087527, 0.9089162485],
[ 0.3844862411, 0.2923344616, 0.2375743054],
[-0.2495892950, -0.3832... | 107Total circles area | 2perl | 4ll5d |
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UTM {
private List<String> tape;
private String blankSymbol;
private ListIterator<String> head;
private Map<Sta... | 103Universal Turing machine | 9java | hghjm |
package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... | 108Totient function | 0go | 6dn3p |
require 'prime'
def cell(n, x, y, start=1)
y, x = y - n/2, x - (n - 1)/2
l = 2 * [x.abs, y.abs].max
d = y >= x? l*3 + x + y: l - x - y
(l - 1)**2 + d + start - 1
end
def show_spiral(n, symbol=nil, start=1)
puts
format =
n.times do |y|
n.times do |x|
i = cell(n,x,y,start)
if symbol
... | 97Ulam spiral (for primes) | 14ruby | b7xkq |
function tm(d,s,e,i,b,t,... r) {
document.write(d, '<br>')
if (i<0||i>=t.length) return
var re=new RegExp(b,'g')
write('*',s,i,t=t.split(''))
var p={}; r.forEach(e=>((s,r,w,m,n)=>{p[s+'.'+r]={w,n,m:[0,1,-1][1+'RL'.indexOf(m)]}})(... e.split(/[ .:,]+/)))
for (var n=1; s!=e; n+=1) {
with (p[s+'.'+t[i]]) t[i]=w,s=... | 103Universal Turing machine | 10javascript | aka10 |
import Control.Monad (when)
import Data.Bool (bool)
totient
:: (Integral a)
=> a -> a
totient n
| n == 0 = 1
| n < 0 = totient (-n)
| otherwise = loop n n 2
where
loop !m !tot !i
| i * i > m = bool tot (tot - (tot `div` m)) (1 < m)
| m `mod` i == 0 = loop m_ tot_ i_
| otherwise = l... | 108Totient function | 8haskell | j5u7g |
null | 106Trabb Pardo–Knuth algorithm | 11kotlin | p7jb6 |
use std::fmt;
enum Direction { RIGHT, UP, LEFT, DOWN }
use ulam::Direction::*; | 97Ulam spiral (for primes) | 15rust | pjqbu |
object Ulam extends App {
generate(9)()
generate(9)('*')
private object Direction extends Enumeration { val RIGHT, UP, LEFT, DOWN = Value }
private def generate(n: Int, i: Int = 1)(c: Char = 0) {
assert(n > 1, "n > 1")
val s = new Array[Array[String]](n).transform {_ => new Array[Strin... | 97Ulam spiral (for primes) | 16scala | eb8ab |
typedef struct {
const char *name, *id, *dept;
int sal;
} person;
person ppl[] = {
{, , , 32000},
{, , , 47000},
{, , , 53500},
{, , , 18000},
{, , , 27800},
{, , , 41500},
{, , , 49500},
{, , , 21900},
{, , , 15900},
{, , , 19250},
{, , , 27... | 115Top rank per group | 5c | 7u6rg |
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
public class TonelliShanks {
private static final BigInteger ZERO = BigInteger.ZERO;
private static final BigInteger ONE = BigInteger.ONE;
private static final... | 109Tonelli-Shanks algorithm | 9java | rvlg0 |
from collections import namedtuple
Circle = namedtuple(, )
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-0.249589295... | 107Total circles area | 3python | g224h |
function f (x) return math.abs(x)^0.5 + 5*x^3 end
function reverse (t)
local rev = {}
for i, v in ipairs(t) do rev[#t - (i-1)] = v end
return rev
end
local sequence, result = {}
print("Enter 11 numbers...")
for n = 1, 11 do
io.write(n .. ": ")
sequence[n] = io.read()
end
for _, x in ipairs(reverse... | 106Trabb Pardo–Knuth algorithm | 1lua | 1jhpo |
loop do
print
expr = gets.strip.downcase
break if expr.empty?
vars = expr.scan(/\p{Alpha}+/)
if vars.empty?
puts
next
end
vars.each {|v| print }
puts
prefix = []
suffix = []
vars.each do |v|
prefix <<
suffix <<
end
body = vars.inject() {|str, v| str + }
body += ' +... | 98Truth table | 14ruby | krehg |
(defn walk [node f order]
(when node
(doseq [o order]
(if (= o:visit)
(f (:val node))
(walk (node o) f order)))))
(defn preorder [node f]
(walk node f [:visit:left:right]))
(defn inorder [node f]
(walk node f [:left:visit:right]))
(defn postorder [node f]
(walk node f [:left:right:visit... | 113Tree traversal | 6clojure | l6ncb |
null | 109Tonelli-Shanks algorithm | 11kotlin | vm621 |
null | 103Universal Turing machine | 11kotlin | 42457 |
public class TotientFunction {
public static void main(String[] args) {
computePhi();
System.out.println("Compute and display phi for the first 25 integers.");
System.out.printf("n Phi IsPrime%n");
for ( int n = 1 ; n <= 25 ; n++ ) {
System.out.printf("%2d %2d %b%n", n... | 108Totient function | 9java | u9mvv |
>>> from itertools import permutations
>>> def f1(p):
i = 0
while True:
p0 = p[0]
if p0 == 1: break
p[:p0] = p[:p0][::-1]
i += 1
return i
>>> def fannkuch(n):
return max(f1(list(p)) for p in permutations(range(1, n+1)))
>>> for n in range(1, 11): print(n,fannkuch(n))
1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
... | 104Topswops | 3python | todfw |
use std::{
collections::HashMap,
fmt::{Display, Formatter},
iter::FromIterator,
}; | 98Truth table | 15rust | b7wkx |
topswops <- function(x){
i <- 0
while(x[1]!= 1){
first <- x[1]
if(first == length(x)){
x <- rev(x)
} else{
x <- c(x[first:1], x[(first+1):length(x)])
}
i <- i + 1
}
return(i)
}
library(iterpc)
result <- NULL
for(i in 1:10){
I <- iterpc(i, labels = 1:i, ordered = T)
A <- g... | 104Topswops | 13r | iq8o5 |
use bigint;
use ntheory qw(is_prime powmod kronecker);
sub tonelli_shanks {
my($n,$p) = @_;
return if kronecker($n,$p) <= 0;
my $Q = $p - 1;
my $S = 0;
$Q >>= 1 and $S++ while 0 == $Q%2;
return powmod($n,int(($p+1)/4), $p) if $S == 1;
my $c;
for $n (2..$p) {
next if kronecker($... | 109Tonelli-Shanks algorithm | 2perl | 0e1s4 |
null | 103Universal Turing machine | 1lua | gvg4j |
(use '[clojure.contrib.seq-utils :only (group-by)])
(defstruct employee :Name :ID :Salary :Department)
(def data
(->> '(("Tyler Bennett" E10297 32000 D101)
("John Rappl" E21437 47000 D050)
("George Woltman" E00127 53500 D101)
("Adam Smith" E63535 18000 D202)
("Clai... | 115Top rank per group | 6clojure | p7lbd |
package main
import (
"errors"
"fmt"
)
func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
var runes []rune
inEscape := false
for _, r := range s {
switch {
case inEscape:
inEscape = false
fallthrough
default:
runes = append(runes, r)
case r == escape:
inEscape = tr... | 112Tokenize a string with escaping | 0go | kg2hz |
circles = [
[ 1.6417233788, 1.6121789534, 0.0848270516],
[-1.4944608174, 1.2077959613, 1.1039549836],
[ 0.6110294452, -0.6907087527, 0.9089162485],
[ 0.3844862411, 0.2923344616, 0.2375743054],
[-0.2495892950, -0.3832854473, 1.0845181219],
[ 1.7813504266, 1.6178237031, 0.8162655711],
[-0.1985249206, -0... | 107Total circles area | 14ruby | 7uuri |
null | 108Totient function | 11kotlin | 9ztmh |
use ntheory ":all";
sub isltrunc {
my $n = shift;
return (is_prime($n) && $n !~ /0/ && ($n < 10 || isltrunc(substr($n,1))));
}
sub isrtrunc {
my $n = shift;
return (is_prime($n) && $n !~ /0/ && ($n < 10 || isrtrunc(substr($n,0,-1))));
}
for (reverse @{primes(1e6)}) {
if (isltrunc($_)) { print "ltrunc: $_\n"; ... | 102Truncatable primes | 2perl | d8fnw |
def legendre(a, p):
return pow(a, (p - 1)
def tonelli(n, p):
assert legendre(n, p) == 1,
q = p - 1
s = 0
while q% 2 == 0:
q
s += 1
if s == 1:
return pow(n, (p + 1)
for z in range(2, p):
if p - 1 == legendre(z, p):
break
c = pow(z, q, p)
... | 109Tonelli-Shanks algorithm | 3python | 8wa0o |
splitEsc :: (Foldable t1, Eq t) => t -> t -> t1 t -> [[t]]
splitEsc sep esc = reverse . map reverse . snd . foldl process (0, [[]])
where process (st, r:rs) ch
| st == 0 && ch == esc = (1, r:rs)
| st == 0 && ch == sep = (0, []:r:rs)
| st == 1 && sep == ... | 112Tokenize a string with escaping | 8haskell | nsaie |
null | 108Totient function | 1lua | c3z92 |
def f1(a)
i = 0
while (a0 = a[0]) > 1
a[0...a0] = a[0...a0].reverse
i += 1
end
i
end
def fannkuch(n)
[*1..n].permutation.map{|a| f1(a)}.max
end
for n in 1..10
puts % [n, fannkuch(n)]
end | 104Topswops | 14ruby | 3ntz7 |
print "Enter 11 numbers:\n";
for ( 1..11 ) {
$number = <STDIN>;
chomp $number;
push @sequence, $number;
}
for $n (reverse @sequence) {
my $result = sqrt( abs($n) ) + 5 * $n**3;
printf "f(%6.2f )%s\n", $n, $result > 400 ? " too large!" : sprintf "=%6.2f", $result
} | 106Trabb Pardo–Knuth algorithm | 2perl | yft6u |
int main(void)
{
char *a[5];
const char *s=;
int n=0, nn;
char *ds=strdup(s);
a[n]=strtok(ds, );
while(a[n] && n<4) a[++n]=strtok(NULL, );
for(nn=0; nn<=n; ++nn) printf(, a[nn]);
putchar('\n');
free(ds);
return 0;
} | 116Tokenize a string | 5c | f8pd3 |
declare -a B=( e e e e e e e e e )
function show(){
local -i p POS=${1:-9}; local UL BOLD="\e[1m" GREEN="\e[32m" DIM="\e[2m" OFF="\e[m" ULC="\e[4m"
for p in 0 1 2 3 4 5 6 7 8; do
[[ p%3 -eq 0 ]] && printf " "
UL=""; [[ p/3 -lt 2 ]] && UL=$ULC
... | 117Tic-tac-toe | 4bash | q15xu |
null | 114Thue-Morse | 0go | xpgwf |
thueMorsePxs :: [[Int]]
thueMorsePxs = iterate ((++) <*> map (1 -)) [0]
main :: IO ()
main = print $ thueMorsePxs !! 5 | 114Thue-Morse | 8haskell | yfs66 |
import java.util.*;
public class TokenizeStringWithEscaping {
public static void main(String[] args) {
String sample = "one^|uno||three^^^^|four^^^|^cuatro|";
char separator = '|';
char escape = '^';
System.out.println(sample);
try {
System.out.println(tokenize... | 112Tokenize a string with escaping | 9java | q1jxa |
package main
import (
"fmt"
"strings"
)
var data = `
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys... | 110Topological sort | 0go | wbjeg |
use itertools::Itertools;
fn solve(deck: &[usize]) -> usize {
let mut counter = 0_usize;
let mut shuffle = deck.to_vec();
loop {
let p0 = shuffle[0];
if p0 == 1 {
break;
}
shuffle[..p0].reverse();
counter += 1;
}
counter
} | 104Topswops | 15rust | 6dz3l |
object Fannkuch extends App {
def fannkuchen(l: List[Int], n: Int, i: Int, acc: Int): Int = {
def flips(l: List[Int]): Int = (l: @unchecked) match {
case 1 :: ls => 0
case (n :: ls) =>
val splitted = l.splitAt(n)
flips(splitted._2.reverse_:::(splitted._1)) + 1
}
def rotateLef... | 104Topswops | 16scala | 9zym5 |
function tokenize(s, esc, sep) {
for (var a=[], t='', i=0, e=s.length; i<e; i+=1) {
var c = s.charAt(i)
if (c == esc) t+=s.charAt(++i)
else if (c != sep) t+=c
else a.push(t), t=''
}
a.push(t)
return a
}
var s = 'one^|uno||three^^^^|four^^^|^cuatro|'
document.write(s, '<br>')
for (var a=tokenize(s,'^','|... | 112Tokenize a string with escaping | 10javascript | iq1ol |
import Data.List ((\\), elemIndex, intersect, nub)
import Data.Bifunctor (bimap, first)
combs 0 _ = [[]]
combs _ [] = []
combs k (x:xs) = ((x:) <$> combs (k - 1) xs) ++ combs k xs
depLibs :: [(String, String)]
depLibs =
[ ( "des_system_lib"
, "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee")
,... | 110Topological sort | 8haskell | 6do3k |
int identity(int x) { return x; }
int sum(int s)
{
int i;
for(i=0; i < 1000000; i++) s += i;
return s;
}
double time_it(int (*action)(int), int arg)
{
struct timespec tsi, tsf;
clock_gettime(CLOCKTYPE, &tsi);
action(arg);
clock_gettime(CLOCKTYPE, &tsf);
double elaps_s = difftime(tsf.tv_sec, ... | 118Time a function | 5c | d0hnv |
public class ThueMorse {
public static void main(String[] args) {
sequence(6);
}
public static void sequence(int steps) {
StringBuilder sb1 = new StringBuilder("0");
StringBuilder sb2 = new StringBuilder("1");
for (int i = 0; i < steps; i++) {
String tmp = sb1.t... | 114Thue-Morse | 9java | d01n9 |
(function(steps) {
'use strict';
var i, tmp, s1 = '0', s2 = '1';
for (i = 0; i < steps; i++) {
tmp = s1;
s1 += s2;
s2 += tmp;
}
console.log(s1);
})(6); | 114Thue-Morse | 10javascript | 6dq38 |
package main
import (
"fmt"
"math"
)
const d = 30.
const r = d * math.Pi / 180
var s = .5
var c = math.Sqrt(3) / 2
var t = 1 / math.Sqrt(3)
func main() {
fmt.Printf("sin(%9.6f deg) =%f\n", d, math.Sin(d*math.Pi/180))
fmt.Printf("sin(%9.6f rad) =%f\n", r, math.Sin(r))
fmt.Printf("cos(%9.6f deg) =... | 111Trigonometric functions | 0go | xpjwf |
(apply str (interpose "." (.split #"," "Hello,How,Are,You,Today"))) | 116Tokenize a string | 6clojure | yfx6b |
fun thueMorse(n: Int): String {
val sb0 = StringBuilder("0")
val sb1 = StringBuilder("1")
repeat(n) {
val tmp = sb0.toString()
sb0.append(sb1)
sb1.append(tmp)
}
return sb0.toString()
}
fun main() {
for (i in 0..6) println("$i: ${thueMorse(i)}")
} | 114Thue-Morse | 11kotlin | 0ejsf |
null | 112Tokenize a string with escaping | 11kotlin | 1j5pd |
use utf8;
binmode STDOUT, ":utf8";
sub gcd {
my ($u, $v) = @_;
while ($v) {
($u, $v) = ($v, $u % $v);
}
return abs($u);
}
push @, 0;
for $t (1..10000) {
push @, scalar grep { 1 == gcd($_,$t) } 1..$t;
}
printf "(%2d) =%3d%s\n", $_, $[$_], $_ - $[$_] - 1 ? '' : ' Prime' for 1 .. 25;
print "\n";
for $l... | 108Totient function | 2perl | wbke6 |
def radians = Math.PI/4
def degrees = 45
def d2r = { it*Math.PI/180 }
def r2d = { it*180/Math.PI }
println "sin(\u03C0/4) = ${Math.sin(radians)} == sin(45\u00B0) = ${Math.sin(d2r(degrees))}"
println "cos(\u03C0/4) = ${Math.cos(radians)} == cos(45\u00B0) = ${Math.cos(d2r(degrees))}"
println "tan(\u03C0/4) = ${Math.t... | 111Trigonometric functions | 7groovy | p75bo |
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type , or for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s'% (x, v if v<=400 else )
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11... | 106Trabb Pardo–Knuth algorithm | 3python | mtzyh |
S <- scan(n=11)
f <- function(x) sqrt(abs(x)) + 5*x^3
for (i in rev(S)) {
res <- f(i)
if (res > 400)
print("Too large!")
else
print(res)
} | 106Trabb Pardo–Knuth algorithm | 13r | zinth |
(defn fib []
(map first
(iterate
(fn [[a b]] [b (+ a b)])
[0 1])))
(time (take 100 (fib))) | 118Time a function | 6clojure | 6da3q |
int b[3][3];
int check_winner()
{
int i;
for (i = 0; i < 3; i++) {
if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0])
return b[i][0];
if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i])
return b[0][i];
}
if (!b[1][1]) return 0;
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0];
... | 117Tic-tac-toe | 5c | 0egst |
ThueMorse = {sequence = "0"}
function ThueMorse:show ()
print(self.sequence)
end
function ThueMorse:addBlock ()
local newBlock = ""
for bit = 1, self.sequence:len() do
if self.sequence:sub(bit, bit) == "1" then
newBlock = newBlock .. "0"
else
newBlock = newBlock .. ... | 114Thue-Morse | 1lua | 8wh0e |
function tokenise (str, sep, esc)
local strList, word, escaped, ch = {}, "", false
for pos = 1, #str do
ch = str:sub(pos, pos)
if ch == esc then
if escaped then
word = word .. ch
escaped = false
else
escaped = true
... | 112Tokenize a string with escaping | 1lua | ah41v |
use strict;
use warnings;
sub run_utm {
my %o = @_;
my $st = $o{state} // die "init head state undefined";
my $blank = $o{blank} // die "blank symbol undefined";
my @rules = @{$o{rules}} or die "rules undefined";
my @tape = $o{tape} ? @{$o{tape}} : ($blank);
my $halt = $o{halt};
my $pos = $o{pos} // 0;
$pos +... | 103Universal Turing machine | 2perl | isio3 |
fromDegrees :: Floating a => a -> a
fromDegrees deg = deg * pi / 180
toDegrees :: Floating a => a -> a
toDegrees rad = rad * 180 / pi
main :: IO ()
main =
mapM_
print
[ sin (pi / 6)
, sin (fromDegrees 30)
, cos (pi / 6)
, cos (fromDegrees 30)
, tan (pi / 6)
, tan (fromDegrees 30)
, a... | 111Trigonometric functions | 8haskell | yfo66 |
maxprime = 1000000
def primes(n):
multiples = set()
prime = []
for i in range(2, n+1):
if i not in multiples:
prime.append(i)
multiples.update(set(range(i*i, n+1, i)))
return prime
def truncatableprime(n):
'Return a longest left and right truncatable primes below n'... | 102Truncatable primes | 3python | fotde |
import java.util.*;
public class TopologicalSort {
public static void main(String[] args) {
String s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,"
+ "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys";
Graph g = new Graph(s, new int[][]{
{2, 0}, {... | 110Topological sort | 9java | nswih |
const libs =
`des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
d... | 110Topological sort | 10javascript | 3n8z0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.