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, ss)
c[1] = true
for p := 2; ; {
p2 := p * p
if p2 >= ss {
break
}
for i := p2; i < ss; i += p {
c[i] = true
}
for {
p++
if !c[p] {
break
}
}
}
}
func search(digits, pot int, s string, truncFunc func(n, pot int) int) bool {
n := pot - 1
pot /= 10
smaller:
for ; n >= pot; n -= 2 {
for tn, tp := n, pot; tp > 0; tp /= 10 {
if tn < tp || c[tn] {
continue smaller
}
tn = truncFunc(tn, tp)
}
fmt.Println("max", s, "truncatable:", n)
return true
}
if digits > 1 {
return search(digits-1, pot, s, truncFunc)
}
return false
} | 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("($_?'T':'F')", @vars, $s)).",\"\\n\")";
$s = "for my $_ (0, 1) { $s }" for (reverse @vars);
eval $s;
}
truth_table 'A ^ A_1';
truth_table 'foo & bar | baz';
truth_table 'Jim & (Spock ^ Bones) | Scotty'; | 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) 10
main = do
let (ltp, rtp) = (head. filter leftT &&& head. filter rightT) primes1e6
putStrLn $ "Left truncatable " ++ show ltp
putStrLn $ "Right truncatable " ++ show rtp | 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 makeSolution(uint64_t root1, uint64_t root2, bool exists) {
struct Solution sol;
sol.root1 = root1;
sol.root2 = root2;
sol.exists = exists;
return sol;
}
struct Solution ts(uint64_t n, uint64_t p) {
uint64_t q = p - 1;
uint64_t ss = 0;
uint64_t z = 2;
uint64_t c, r, t, m;
if (modpow(n, (p - 1) / 2, p) != 1) {
return makeSolution(0, 0, false);
}
while ((q & 1) == 0) {
ss += 1;
q >>= 1;
}
if (ss == 1) {
uint64_t r1 = modpow(n, (p + 1) / 4, p);
return makeSolution(r1, p - r1, true);
}
while (modpow(z, (p - 1) / 2, p) != p - 1) {
z++;
}
c = modpow(z, q, p);
r = modpow(n, (q + 1) / 2, p);
t = modpow(n, q, p);
m = ss;
while (true) {
uint64_t i = 0, zz = t;
uint64_t b = c, e;
if (t == 1) {
return makeSolution(r, p - r, true);
}
while (zz != 1 && i < (m - 1)) {
zz = zz * zz % p;
i++;
}
e = m - i - 1;
while (e > 0) {
b = b * b % p;
e--;
}
r = r * b % p;
c = b * b % p;
t = t * c % p;
m = i;
}
}
void test(uint64_t n, uint64_t p) {
struct Solution sol = ts(n, p);
printf(, n);
printf(, p);
if (sol.exists) {
printf(, sol.root1);
printf(, sol.root2);
} else {
printf();
}
printf();
}
int main() {
test(10, 13);
test(56, 101);
test(1030, 10009);
test(1032, 10009);
test(44402, 100049);
return 0;
} | 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
approximatedArea cs box_side = (fromIntegral count) * dx * dy
where
x_min = minimum [cx c - cr c | c <- circles]
x_max = maximum [cx c + cr c | c <- circles]
y_min = minimum [cy c - cr c | c <- circles]
y_max = maximum [cy c + cr c | c <- circles]
dx = (x_max - x_min) / (fromIntegral box_side)
dy = (y_max - y_min) / (fromIntegral box_side)
count = length [0 | r <- [0 .. box_side - 1],
c <- [0 .. box_side - 1],
isInsideAny (posx c) (posy r) circles]
posy r = y_min + (fromIntegral r) * dy
posx c = x_min + (fromIntegral c) * dx
circles :: [Circle]
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.2495892950) (-0.3832854473) 1.0845181219,
Circle ( 1.7813504266) ( 1.6178237031) 0.8162655711,
Circle (-0.1985249206) (-0.8343333301) 0.0538864941,
Circle (-1.7011985145) (-0.1263820964) 0.4776976918,
Circle (-0.4319462812) ( 1.4104420482) 0.7886291537,
Circle ( 0.2178372997) (-0.9499557344) 0.0357871187,
Circle (-0.6294854565) (-1.3078893852) 0.7653357688,
Circle ( 1.7952608455) ( 0.6281269104) 0.2727652452,
Circle ( 1.4168575317) ( 1.0683357171) 1.1016025378,
Circle ( 1.4637371396) ( 0.9463877418) 1.1846214562,
Circle (-0.5263668798) ( 1.7315156631) 1.4428514068,
Circle (-1.2197352481) ( 0.9144146579) 1.0727263474,
Circle (-0.1389358881) ( 0.1092805780) 0.7350208828,
Circle ( 1.5293954595) ( 0.0030278255) 1.2472867347,
Circle (-0.5258728625) ( 1.3782633069) 1.3495508831,
Circle (-0.1403562064) ( 0.2437382535) 1.3804956588,
Circle ( 0.8055826339) (-0.0482092025) 0.3327165165,
Circle (-0.6311979224) ( 0.7184578971) 0.2491045282,
Circle ( 1.4685857879) (-0.8347049536) 1.3670667538,
Circle (-0.6855727502) ( 1.6465021616) 1.0593087096,
Circle ( 0.0152957411) ( 0.0638919221) 0.9771215985]
main = putStrLn $ "Approximated area: " ++
(show $ approximatedArea circles 5000) | 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 = *list = realloc(lst, ++*len * sizeof(item_t));
i = *len - 1;
memset(lst + i, 0, sizeof(item_t));
lst[i].idx = i;
lst[i].name = name;
return i;
}
void add_dep(item it, int i)
{
if (it->idx == i) return;
it->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));
it->deps[it->n_deps++] = i;
}
int parse_input(item *ret)
{
int n_items = 0;
int i, parent, idx;
item list = 0;
char *s, *e, *word, *we;
for (s = input; ; s = 0) {
if (!(s = strtok_r(s, , &e))) break;
for (i = 0, word = s; ; i++, word = 0) {
if (!(word = strtok_r(word, , &we))) break;
idx = get_item(&list, &n_items, word);
if (!i) parent = idx;
else add_dep(list + parent, idx);
}
}
*ret = list;
return n_items;
}
int get_depth(item list, int idx, int bad)
{
int max, i, t;
if (!list[idx].deps)
return list[idx].depth = 1;
if ((t = list[idx].depth) < 0) return t;
list[idx].depth = bad;
for (max = i = 0; i < list[idx].n_deps; i++) {
if ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {
max = t;
break;
}
if (max < t + 1) max = t + 1;
}
return list[idx].depth = max;
}
int main()
{
int i, j, n, bad = -1, max, min;
item items;
n = parse_input(&items);
for (i = 0; i < n; i++)
if (!items[i].depth && get_depth(items, i, bad) < 0) bad--;
for (i = 0, max = min = 0; i < n; i++) {
if (items[i].depth > max) max = items[i].depth;
if (items[i].depth < min) min = items[i].depth;
}
printf();
for (i = min; i <= max; i++) {
if (!i) continue;
if (i < 0) printf();
else printf(, i);
for (j = 0; j < n || !putchar('\n'); j++)
if (items[j].depth == i)
printf(, items[j].name);
}
return 0;
} | 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;
if (d + best[i] <= best[n])
return;
}
int[] deck2 = deck.clone();
for (int i = 1; i < n; i++) {
final int k = 1 << i;
if (deck2[i] == -1) {
if ((f & k) != 0)
continue;
} else if (deck2[i] != i)
continue;
deck2[0] = i;
for (int j = i - 1; j >= 0; j--)
deck2[i - j] = deck[j]; | 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, temp * 180 / pi);
temp = acos(cos(radians));
printf(, temp, temp * 180 / pi);
temp = atan(tan(radians));
printf(, temp, temp * 180 / pi);
return 0;
} | 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) { st[6]? (st[4] & st[5]): true },
->(st) { st.first(6).count(true) == 3 },
->(st) { st[10] & st[11] },
->(st) { st[6..8].one? },
->(st) { st[0,11].count(true) == 4 },
]
Result = Struct.new(:truths, :consistency)
results = [true, false].repeated_permutation(12).map do |truths|
Result.new(truths, constraints.zip(truths).map {|cn,truth| cn[truths] == truth })
end
puts ,
results.find {|r| r.consistency.all? }.truths.to_s
puts
near_misses = results.select {|r| r.consistency.count(false) == 1 }
near_misses.each do |r|
puts , r.truths.to_s
end | 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 check4: Boolean = s(4) == (!s(5) || s(6) && s(7))
def check5: Boolean = s(5) == (!s(2) && !s(3) && !s(4))
def check6: Boolean = {
var count = 0
for (k <- 1 to 11 by 2) if (s(k)) count += 1
s(6) == (count == 4)
}
def check7: Boolean = s(7) == ((s(2) || s(3)) && !(s(2) && s(3)))
def check8: Boolean = s(8) == (!s(7) || s(5) && s(6))
def check9: Boolean = {
var count = 0
for (k <- 1 to 6) if (s(k)) count += 1
s(9) == (count == 3)
}
def check10: Boolean = s(10) == (s(11) && s(12))
def check11: Boolean = {
var count = 0
for (k <- 7 to 9) if (s(k)) count += 1
s(11) == (count == 1)
}
def check12: Boolean = {
var count = 0
for (k <- 1 to 11) if (s(k)) count += 1
s(12) == (count == 4)
}
def check(): Unit = {
if (check2 && check3 && check4 && check5 && check6 && check7 && check8 && check9 && check10 && check11 && check12) {
for (k <- 1 to 12) if (s(k)) print(k + " ")
println()
count += 1
}
}
def recurseAll(k: Int): Unit = {
if (k == 13) check()
else {
s(k) = false
recurseAll(k + 1)
s(k) = true
recurseAll(k + 1)
}
}
}
object LogicPuzzle extends App {
val p = new LogicPuzzle
p.s(1) = true
p.recurseAll(2)
println()
println(s"${p.count} Solutions found.")
} | 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,False,True] + [True,False]*(top
for x in range(3, 1 + int(sqrt(top))):
if not is_prime[x]: continue
for i in range(x*x, top, x*2):
is_prime[i] = False
cell_str = lambda x: f(x) if is_prime[x] else space
f = lambda _: symbol
if space == None: space = ' '*len(symbol)
if not len(symbol):
max_str = len(str(n*n + start - 1))
if space == None: space = '.'*max_str + ' '
f = lambda x: ('%' + str(max_str) + 'd ')%x
for y in range(n):
print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)]))
print()
show_spiral(10, symbol=u'', space=u'')
show_spiral(9, symbol='', space=' - ') | 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 gcd(b, m) == 1 and gcd(e, m) == 1) "
[b e m]
(.modPow (biginteger b) (biginteger e) (biginteger m)))
(defn legendre [a p]
(modpow a (quot (dec p) 2) p)
)
(defn tonelli [n p]
" Following Wikipedia https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm "
(assert (= (legendre n p) 1) "not a square (mod p)")
(loop [q (dec p)
s 0]
(if (zero? (rem q 2))
(recur (quot q 2) (inc s))
(if (= s 1)
(modpow n (quot (inc p) 4) p)
(let [z (find-first #(= (dec p) (legendre % p)) (range 2 p))]
(loop [
M s
c (modpow z q p)
t (modpow n q p)
R (modpow n (quot (inc q) 2) p)]
(if (= t 1)
R
(let [i (long (find-first #(= 1 (modpow t (bit-shift-left 1 %) p)) (range 1 M)))
b (modpow c (bit-shift-left 1 (- M i 1)) p)
M i
c (modpow b 2 p)
t (rem (* t c) p)
R (rem (* R b) p)]
(recur M c t R)
)
)
)
)
)
)
)
)
(doseq [[n p] [[10, 13], [56, 101], [1030, 10009], [44402, 100049],
[665820697, 1000000009], [881398088036, 1000000000039],
[41660815127637347468140745042827704103445750172002, 100000000000000000000000000000000000000000000000577]]
:let [r (tonelli n p)]]
(println (format "n:%5d p:%d \n\troots:%5d%5d" (biginteger n) (biginteger p) (biginteger r) (biginteger (- p r))))) | 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(0), ncol=n, nrow=n, byrow=TRUE);
for (i in 1:n2) {
if(isPrime(i)) {M[x,y]=1};
if(dir=="R") {if(xmx>0) {x=x+1;xmx=xmx-1}
else {dir="U";ymx=cnt;y=y-1;ymx=ymx-1}; next};
if(dir=="U") {if(ymx>0) {y=y-1;ymx=ymx-1}
else {dir="L";cnt=cnt+1;xmx=cnt;x=x-1;xmx=xmx-1}; next};
if(dir=="L") {if(xmx>0) {x=x-1;xmx=xmx-1}
else {dir="D";ymx=cnt;y=y+1;ymx=ymx-1}; next};
if(dir=="D") {if(ymx>0) {y=y+1;ymx=ymx-1}
else {dir="R";cnt=cnt+1;xmx=cnt;x=x+1;xmx=xmx-1}; next};
};
plotmat(M, fn, clr, ttl,,psz);
cat(" *** END:",date(),"\n");
}
plotulamspirR(100, "red", "UlamSpiralR1", "Ulam Spiral: ");
plotulamspirR(200, "red", "UlamSpiralR2", "Ulam Spiral: ",1240); | 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( , q );
for( i=0; i<q; ++i )
printf( , i+1, list[i] );
free( list );
}
return 0;
}
unsigned int ElQ( const char *s, char sep, char esc ) {
unsigned int q, e;
const char *p;
for( e=0, q=1, p=s; *p; ++p ) {
if( *p == esc )
e = !e;
else if( *p == sep )
q += !e;
else e = 0;
}
return q;
}
Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
Str *list = NULL;
*q = ElQ( s, sep, esc );
list = malloc( *q * sizeof(Str) );
if( list != NULL ) {
unsigned int e, i;
char *p;
i = 0;
list[i++] = s;
for( e=0, p=s; *p; ++p ) {
if( *p == esc ) {
e = !e;
}
else if( *p == sep && !e ) {
list[i++] = p+1;
*p = '\0';
}
else {
e = 0;
}
}
}
return list;
} | 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 to an empty set."
[item]
(dep item '()))
(defn pair-dep
"Invokes dep after destructuring item and items from the argument."
[[item items]]
(dep item items))
(defn default-deps
"Constructs a default dependence map taking every item
in the argument to an empty set"
[items]
(apply merge-with union (map empty-dep (flatten items))))
(defn declared-deps
"Constructs a dependence map from a list containaining
alternating items and list of their predecessor items."
[items]
(apply merge-with union (map pair-dep (partition 2 items))))
(defn deps
"Constructs a full dependence map containing both explicitly
represented dependences and default empty dependences for
items without explicit predecessors."
[items]
(merge (default-deps items) (declared-deps items)))
(defn no-dep-items
"Returns all keys from the argument which have no (i.e. empty) dependences."
[deps]
(filter #(empty? (deps %)) (keys deps)))
(defn remove-items
"Returns a dependence map with the specified items removed from keys
and from all dependence sets of remaining keys."
[deps items]
(let [items-to-remove (set items)
remaining-keys (difference (set (keys deps)) items-to-remove)
remaining-deps (fn [x] (dep x (difference (deps x) items-to-remove)))]
(apply merge (map remaining-deps remaining-keys))))
(defn topo-sort-deps
"Given a dependence map, returns either a list of items in which each item
follows all of its predecessors, or a string showing the items among which
there is a cyclic dependence preventing a linear order."
[deps]
(loop [remaining-deps deps
result '()]
(if (empty? remaining-deps)
(reverse result)
(let [ready-items (no-dep-items remaining-deps)]
(if (empty? ready-items)
(str "ERROR: cycles remain among " (keys remaining-deps))
(recur (remove-items remaining-deps ready-items)
(concat ready-items result)))))))
(defn topo-sort
"Given a list of alternating items and predecessor lists, constructs a
full dependence map and then applies topo-sort-deps to that map."
[items]
(topo-sort-deps (deps items))) | 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 radians) " " (tan (* degrees dtor))))
(println (str (asin (sin radians) ) " " (* (asin (sin (* degrees dtor))) rtod)))
(println (str (acos (cos radians) ) " " (* (acos (cos (* degrees dtor))) rtod)))
(println (str (atan (tan radians) ) " " (* (atan (tan (* degrees dtor))) rtod))) | 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) $
reverse x | 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(names)):
env = dict(zip(names, values))
print(' '.join(str(v) for v in values), ':', eval(code, env)) | 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 ++ "]"
left = map show $ reverse $ take 10 lts
right = map show $ take 10 rts
tape blank lts rts | null rts = Tape blank left blanks
| otherwise = Tape (head rts) left right
where blanks = repeat blank
left = reverse lts ++ blanks
right = tail rts ++ blanks
step rules (state, Tape x (lh:lts) (rh:rts)) = (state', tape')
where Action x' dir state' = rules state x
tape' = move dir
move Stay = Tape x' (lh:lts) (rh:rts)
move MLeft = Tape lh lts (x':rh:rts)
move MRight = Tape rh (x':lh:lts) rts
runUTM rules stop start tape = steps ++ [final]
where (steps, final:_) = break ((== stop) . fst) $ iterate (step rules) (start, tape) | 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 {
userInput = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.println("You entered invalid input, exiting");
System.exit(1);
}
input[i] = userInput;
}
for(int j = 10; j >= 0; j--) {
double x = input[j]; double y = f(x);
if( y < 400.0) {
System.out.printf("f(%.2f ) =%.2f\n", x, y);
} else {
System.out.printf("f(%.2f ) =%s\n", x, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
} | 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")
truth_table("A & B")
truth_table("A%^% B")
truth_table("S | (T%^% U)")
truth_table("A%^% (B%^% (C%^% D))") | 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)
destroy_tree(n->right);
free(n);
}
void preorder(node n, void (*f)(int))
{
f(n->value);
if (n->left)
preorder(n->left, f);
if (n->right)
preorder(n->right, f);
}
void inorder(node n, void (*f)(int))
{
if (n->left)
inorder(n->left, f);
f(n->value);
if (n->right)
inorder(n->right, f);
}
void postorder(node n, void (*f)(int))
{
if (n->left)
postorder(n->left, f);
if (n->right)
postorder(n->right, f);
f(n->value);
}
typedef struct qnode_s
{
struct qnode_s* next;
node value;
} *qnode;
typedef struct { qnode begin, end; } queue;
void enqueue(queue* q, node n)
{
qnode node = malloc(sizeof(struct qnode_s));
node->value = n;
node->next = 0;
if (q->end)
q->end->next = node;
else
q->begin = node;
q->end = node;
}
node dequeue(queue* q)
{
node tmp = q->begin->value;
qnode second = q->begin->next;
free(q->begin);
q->begin = second;
if (!q->begin)
q->end = 0;
return tmp;
}
int queue_empty(queue* q)
{
return !q->begin;
}
void levelorder(node n, void(*f)(int))
{
queue nodequeue = {};
enqueue(&nodequeue, n);
while (!queue_empty(&nodequeue))
{
node next = dequeue(&nodequeue);
f(next->value);
if (next->left)
enqueue(&nodequeue, next->left);
if (next->right)
enqueue(&nodequeue, next->right);
}
}
void print(int n)
{
printf(, n);
}
int main()
{
node n = tree(1,
tree(2,
tree(4,
tree(7, 0, 0),
0),
tree(5, 0, 0)),
tree(3,
tree(6,
tree(8, 0, 0),
tree(9, 0, 0)),
0));
printf();
preorder(n, print);
printf();
printf();
inorder(n, print);
printf();
printf();
postorder(n, print);
printf();
printf();
levelorder(n, print);
printf();
destroy_tree(n);
return 0;
} | 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 = shift @$d;
if( not $now[$next-1] ) {
$now[$next-1] = $next;
splice @now, 0, 0, reverse splice @now, 0, $next;
$swopped = 1;
next_swop( $max, $level+1, \@now, [ @$d ] );
}
push @$d, $next;
}
$$max = $level if !$swopped and $level > $$max;
}
sub topswops {
my $n = shift;
my @d = 2..$n;
my @p = ( 1, (0) x ($n-1) );
my $max = 0;
next_swop( \$max, 0, \@p, \@d );
return $max;
}
printf "Maximum swops for%2d cards:%2d\n", $_, topswops $_ for 1..10; | 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 {
print(' = ' + String(res));
}
}
function fn(x) {
return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3);
}
function getNumbers(n) {
var nums = [];
print('Enter', n, 'numbers.');
for (var i = 1; i <= n; i++) {
putstr(' ' + i + ': ');
var num = readline();
nums.push(Number(num));
}
return nums;
}
main(); | 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
local is_prime = true
local l = math.floor( i / 10 )
while l > 1 do
if numbers[l] == 0 then
is_prime = false
break
end
l = math.floor( l / 10 )
end
if is_prime then
max_prime_left = i
end
is_prime = true
local n = 10;
while math.floor( i % 10 ) ~= 0 and n < max_number do
if numbers[ math.floor( i % 10 ) ] ~= 0 then
is_prime = false
break
end
n = n * 10
end
if is_prime then
max_prime_right = i
end
end
end
print( "max_prime_left = ", max_prime_left )
print( "max_prime_right = ", max_prime_right ) | 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 :: Integer -> Integer -> Integer
legendre a p = powMod p a ((p - 1) `div` 2)
tonelli :: Integer -> Integer -> Maybe (Integer, Integer)
tonelli n p | legendre n p /= 1 = Nothing
tonelli n p =
let s = length $ takeWhile even $ iterate (`div` 2) (p-1)
q = shiftR (p-1) s
in if s == 1
then let r = powMod p n ((p+1) `div` 4)
in Just (r, p - r)
else let z = (2 +) . genericLength
$ takeWhile (\i -> p - 1 /= legendre i p)
$ [2..p-1]
in loop s
( powMod p z q )
( powMod p n $ (q+1) `div` 2 )
( powMod p n q )
where
loop m c r t
| (t - 1) `mod` p == 0 = Just (r, p - r)
| otherwise =
let i = (1 +) . genericLength . genericTake (m - 2)
$ takeWhile (\t2 -> (t2 - 1) `mod` p /= 0)
$ iterate (\t2 -> (t2*t2) `mod` p)
$ (t*t) `mod` p
b = powMod p c (2^(m - i - 1))
r' = (r*b) `mod` p
c' = (b*b) `mod` p
t' = (t*c') `mod` p
in loop i c' r' t' | 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.3832854473, 1.0845181219],
[ 1.7813504266, 1.6178237031, 0.8162655711],
[-0.1985249206, -0.8343333301, 0.0538864941],
[-1.7011985145, -0.1263820964, 0.4776976918],
[-0.4319462812, 1.4104420482, 0.7886291537],
[ 0.2178372997, -0.9499557344, 0.0357871187],
[-0.6294854565, -1.3078893852, 0.7653357688],
[ 1.7952608455, 0.6281269104, 0.2727652452],
[ 1.4168575317, 1.0683357171, 1.1016025378],
[ 1.4637371396, 0.9463877418, 1.1846214562],
[-0.5263668798, 1.7315156631, 1.4428514068],
[-1.2197352481, 0.9144146579, 1.0727263474],
[-0.1389358881, 0.1092805780, 0.7350208828],
[ 1.5293954595, 0.0030278255, 1.2472867347],
[-0.5258728625, 1.3782633069, 1.3495508831],
[-0.1403562064, 0.2437382535, 1.3804956588],
[ 0.8055826339, -0.0482092025, 0.3327165165],
[-0.6311979224, 0.7184578971, 0.2491045282],
[ 1.4685857879, -0.8347049536, 1.3670667538],
[-0.6855727502, 1.6465021616, 1.0593087096],
[ 0.0152957411, 0.0638919221, 0.9771215985],
);
my $x_min = min map { $_->[0] - $_->[2] } @circles;
my $x_max = max map { $_->[0] + $_->[2] } @circles;
my $y_min = min map { $_->[1] - $_->[2] } @circles;
my $y_max = max map { $_->[1] + $_->[2] } @circles;
my $box_side = 500;
my $dx = ($x_max - $x_min) / $box_side;
my $dy = ($y_max - $y_min) / $box_side;
my $count = 0;
for my $r (0..$box_side) {
my $y = $y_min + $r * $dy;
for my $c (0..$box_side) {
my $x = $x_min + $c * $dx;
for my $c (@circles) {
$count++ and last if ($x - $$c[0])**2 + ($y - $$c[1])**2 <= $$c[2]**2
}
}
}
printf "Approximated area:%.9f\n", $count * $dx * $dy; | 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<StateTapeSymbolPair, Transition> transitions = new HashMap<StateTapeSymbolPair, Transition>();
private Set<String> terminalStates;
private String initialState;
public UTM(Set<Transition> transitions, Set<String> terminalStates, String initialState, String blankSymbol) {
this.blankSymbol = blankSymbol;
for (Transition t: transitions) {
this.transitions.put(t.from, t);
}
this.terminalStates = terminalStates;
this.initialState = initialState;
}
public static class StateTapeSymbolPair {
private String state;
private String tapeSymbol;
public StateTapeSymbolPair(String state, String tapeSymbol) {
this.state = state;
this.tapeSymbol = tapeSymbol;
} | 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 {
t >>= 1
}
if t > 0 {
n = t
} else {
k = -t
}
t = n - k
}
return n * s
}
func totient(n int) int {
tot := 0
for k := 1; k <= n; k++ {
if gcd(n, k) == 1 {
tot++
}
}
return tot
}
func main() {
fmt.Println(" n phi prime")
fmt.Println("---------------")
count := 0
for n := 1; n <= 25; n++ {
tot := totient(n)
isPrime := n-1 == tot
if isPrime {
count++
}
fmt.Printf("%2d %2d %t\n", n, tot, isPrime)
}
fmt.Println("\nNumber of primes up to 25 =", count)
for n := 26; n <= 100000; n++ {
tot := totient(n)
if tot == n-1 {
count++
}
if n == 100 || n == 1000 || n%10000 == 0 {
fmt.Printf("\nNumber of primes up to%-6d =%d\n", n, count)
}
}
} | 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
print i.prime?? symbol[0]: symbol[1]
else
print format % (i.prime?? i: '')
end
end
puts
end
end
show_spiral(9)
show_spiral(25)
show_spiral(25, ) | 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=n,i+=m
if (i==-1) i=0,t.unshift(b)
else if (i==t.length) t[i]=b
write(n,s,i,t)
}
document.write('<br>')
function write(n, s, i, t) {
t = t.join('')
t = t.substring(0,i) + '<u>' + t.charAt(i) + '</u>' + t.substr(i+1)
document.write((' '+n).slice(-3).replace(/ /g,' '), ': ', s, ' [', t.replace(re,' '), ']', '<br>')
}
}
tm( 'Unary incrementer', | 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 = loop m tot i_
where
i_
| i == 2 = 3
| otherwise = 2 + i
m_ = nextM m
tot_ = tot - (tot `div` i)
nextM !x
| x `mod` i == 0 = nextM $ x `div` i
| otherwise = x
main :: IO ()
main = do
putStrLn "n\tphi\tprime\n
let loop !i !count
| i >= 10 ^ 6 = return ()
| otherwise = do
let i_ = succ i
tot = totient i_
isPrime = tot == pred i_
count_
| isPrime = succ count
| otherwise = count
when (25 >= i_) $
putStrLn $ show i_ ++ "\t" ++ show tot ++ "\t" ++ show isPrime
when
(i_ `elem`
25:
[ 10 ^ k
| k <- [2 .. 6] ]) $
putStrLn $ "Number of primes up to " ++ show i_ ++ " = " ++ show count_
loop (i + 1) count_
loop 0 0 | 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[String](n) }
import Direction._
var dir = RIGHT
var y = n / 2
var x = if (n % 2 == 0) y - 1 else y | 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},
{, , , 27000},
{, , , 57000},
{, , , 29900},
};
int pcmp(const void *a, const void *b)
{
const person *aa = a, *bb = b;
int x = strcmp(aa->dept, bb->dept);
if (x) return x;
return aa->sal > bb->sal ? -1 : aa->sal < bb->sal;
}
void top(int n)
{
int i, rank;
qsort(ppl, N, sizeof(person), pcmp);
for (i = rank = 0; i < N; i++) {
if (i && strcmp(ppl[i].dept, ppl[i - 1].dept)) {
rank = 0;
printf();
}
if (rank++ < n)
printf(, ppl[i].dept, ppl[i].sal, ppl[i].name);
}
}
int main()
{
top(2);
return 0;
} | 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 BigInteger TEN = BigInteger.TEN;
private static final BigInteger TWO = BigInteger.valueOf(2);
private static final BigInteger FOUR = BigInteger.valueOf(4);
private static class Solution {
private BigInteger root1;
private BigInteger root2;
private boolean exists;
Solution(BigInteger root1, BigInteger root2, boolean exists) {
this.root1 = root1;
this.root2 = root2;
this.exists = exists;
}
}
private static Solution ts(Long n, Long p) {
return ts(BigInteger.valueOf(n), BigInteger.valueOf(p));
}
private static Solution ts(BigInteger n, BigInteger p) {
BiFunction<BigInteger, BigInteger, BigInteger> powModP = (BigInteger a, BigInteger e) -> a.modPow(e, p);
Function<BigInteger, BigInteger> ls = (BigInteger a) -> powModP.apply(a, p.subtract(ONE).divide(TWO));
if (!ls.apply(n).equals(ONE)) return new Solution(ZERO, ZERO, false);
BigInteger q = p.subtract(ONE);
BigInteger ss = ZERO;
while (q.and(ONE).equals(ZERO)) {
ss = ss.add(ONE);
q = q.shiftRight(1);
}
if (ss.equals(ONE)) {
BigInteger r1 = powModP.apply(n, p.add(ONE).divide(FOUR));
return new Solution(r1, p.subtract(r1), true);
}
BigInteger z = TWO;
while (!ls.apply(z).equals(p.subtract(ONE))) z = z.add(ONE);
BigInteger c = powModP.apply(z, q);
BigInteger r = powModP.apply(n, q.add(ONE).divide(TWO));
BigInteger t = powModP.apply(n, q);
BigInteger m = ss;
while (true) {
if (t.equals(ONE)) return new Solution(r, p.subtract(r), true);
BigInteger i = ZERO;
BigInteger zz = t;
while (!zz.equals(BigInteger.ONE) && i.compareTo(m.subtract(ONE)) < 0) {
zz = zz.multiply(zz).mod(p);
i = i.add(ONE);
}
BigInteger b = c;
BigInteger e = m.subtract(i).subtract(ONE);
while (e.compareTo(ZERO) > 0) {
b = b.multiply(b).mod(p);
e = e.subtract(ONE);
}
r = r.multiply(b).mod(p);
c = b.multiply(b).mod(p);
t = t.multiply(c).mod(p);
m = i;
}
}
public static void main(String[] args) {
List<Map.Entry<Long, Long>> pairs = List.of(
Map.entry(10L, 13L),
Map.entry(56L, 101L),
Map.entry(1030L, 10009L),
Map.entry(1032L, 10009L),
Map.entry(44402L, 100049L),
Map.entry(665820697L, 1000000009L),
Map.entry(881398088036L, 1000000000039L)
);
for (Map.Entry<Long, Long> pair : pairs) {
Solution sol = ts(pair.getKey(), pair.getValue());
System.out.printf("n =%s\n", pair.getKey());
System.out.printf("p =%s\n", pair.getValue());
if (sol.exists) {
System.out.printf("root1 =%s\n", sol.root1);
System.out.printf("root2 =%s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
System.out.println();
}
BigInteger bn = new BigInteger("41660815127637347468140745042827704103445750172002");
BigInteger bp = TEN.pow(50).add(BigInteger.valueOf(577));
Solution sol = ts(bn, bp);
System.out.printf("n =%s\n", bn);
System.out.printf("p =%s\n", bp);
if (sol.exists) {
System.out.printf("root1 =%s\n", sol.root1);
System.out.printf("root2 =%s\n", sol.root2);
} else {
System.out.println("No solution exists");
}
}
} | 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.2495892950, -0.3832854473, 1.0845181219),
Circle( 1.7813504266, 1.6178237031, 0.8162655711),
Circle(-0.1985249206, -0.8343333301, 0.0538864941),
Circle(-1.7011985145, -0.1263820964, 0.4776976918),
Circle(-0.4319462812, 1.4104420482, 0.7886291537),
Circle( 0.2178372997, -0.9499557344, 0.0357871187),
Circle(-0.6294854565, -1.3078893852, 0.7653357688),
Circle( 1.7952608455, 0.6281269104, 0.2727652452),
Circle( 1.4168575317, 1.0683357171, 1.1016025378),
Circle( 1.4637371396, 0.9463877418, 1.1846214562),
Circle(-0.5263668798, 1.7315156631, 1.4428514068),
Circle(-1.2197352481, 0.9144146579, 1.0727263474),
Circle(-0.1389358881, 0.1092805780, 0.7350208828),
Circle( 1.5293954595, 0.0030278255, 1.2472867347),
Circle(-0.5258728625, 1.3782633069, 1.3495508831),
Circle(-0.1403562064, 0.2437382535, 1.3804956588),
Circle( 0.8055826339, -0.0482092025, 0.3327165165),
Circle(-0.6311979224, 0.7184578971, 0.2491045282),
Circle( 1.4685857879, -0.8347049536, 1.3670667538),
Circle(-0.6855727502, 1.6465021616, 1.0593087096),
Circle( 0.0152957411, 0.0638919221, 0.9771215985)]
def main():
x_min = min(c.x - c.r for c in circles)
x_max = max(c.x + c.r for c in circles)
y_min = min(c.y - c.r for c in circles)
y_max = max(c.y + c.r for c in circles)
box_side = 500
dx = (x_max - x_min) / box_side
dy = (y_max - y_min) / box_side
count = 0
for r in xrange(box_side):
y = y_min + r * dy
for c in xrange(box_side):
x = x_min + c * dx
if any((x-circle.x)**2 + (y-circle.y)**2 <= (circle.r ** 2)
for circle in circles):
count += 1
print , count * dx * dy
main() | 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(sequence)) do
result = f(x)
if result > 400 then print("Overflow!") else print(result) end
end | 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 += ' + eval(expr).to_s'
eval (prefix + [body] + suffix).join()
end | 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]))
(defn queue [& xs]
(when (seq xs)
(apply conj clojure.lang.PersistentQueue/EMPTY xs)))
(defn level-order [root f]
(loop [q (queue root)]
(when-not (empty? q)
(if-let [node (first q)]
(do
(f (:val node))
(recur (conj (pop q) (:left node) (:right node))))
(recur (pop q))))))
(defn vec-to-tree [t]
(if (vector? t)
(let [[val left right] t]
{:val val
:left (vec-to-tree left)
:right (vec-to-tree right)})
t))
(let [tree (vec-to-tree [1 [2 [4 [7]] [5]] [3 [6 [8] [9]]]])
fs '[preorder inorder postorder level-order]
pr-node #(print (format "%2d" %))]
(doseq [f fs]
(print (format "%-12s" (str f ":")))
((resolve f) tree pr-node)
(println))) | 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, phi[n], (phi[n] == n-1));
}
for ( int i = 2 ; i < 8 ; i++ ) {
int max = (int) Math.pow(10, i);
System.out.printf("The count of the primes up to%,10d =%d%n", max, countPrimes(1, max));
}
}
private static int countPrimes(int min, int max) {
int count = 0;
for ( int i = min ; i <= max ; i++ ) {
if ( phi[i] == i-1 ) {
count++;
}
}
return count;
}
private static final int max = 10000000;
private static final int[] phi = new int[max+1];
private static final void computePhi() {
for ( int i = 1 ; i <= max ; i++ ) {
phi[i] = i;
}
for ( int i = 2 ; i <= max ; i++ ) {
if (phi[i] < i) continue;
for ( int j = i ; j <= max ; j += i ) {
phi[j] -= phi[j] / i;
}
}
}
} | 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
9 30
10 38
>>> | 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 <- getall(I)
A <- data.frame(A)
A$flips <- apply(A, 1, topswops)
result <- rbind(result, c(i, max(A$flips)))
} | 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($n,$p) >= 0;
$c = powmod($n, $Q, $p);
last;
}
my $R = powmod($n, ($Q+1) >> 1, $p );
my $t = powmod($n, $Q, $p );
while (($t-1) % $p) {
my $b;
my $t2 = $t**2 % $p;
for (1 .. $S) {
if (0 == ($t2-1)%$p) {
$b = powmod($c, 1 << ($S-1-$_), $p);
$S = $_;
last;
}
$t2 = $t2**2 % $p;
}
$R = ($R * $b) % $p;
$c = $b**2 % $p;
$t = ($t * $c) % $p;
}
$R;
}
my @tests = (
(10, 13),
(56, 101),
(1030, 10009),
(1032, 10009),
(44402, 100049),
(665820697, 1000000009),
(881398088036, 1000000000039),
);
while (@tests) {
$n = shift @tests;
$p = shift @tests;
my $t = tonelli_shanks($n, $p);
if (!$t or ($t**2 - $n) % $p) {
printf "No solution for (%d,%d)\n", $n, $p;
} else {
printf "Roots of%d are (%d,%d) mod%d\n", $n, $t, $p-$t, $p;
}
} | 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)
("Claire Buckman" E39876 27800 D202)
("David McClellan" E04242 41500 D101)
("Rich Holcomb" E01234 49500 D202)
("Nathan Adams" E41298 21900 D050)
("Richard Potter" E43128 15900 D101)
("David Motsinger" E27002 19250 D202)
("Tim Sampair" E03033 27000 D101)
("Kim Arlich" E10001 57000 D190)
("Timothy Grove" E16398 29900 D190))
(map #(apply (partial struct employee) %))))
(doseq [[dep emps] (group-by :Department data)]
(println "Department:" dep)
(doseq [e (take 3 (reverse (sort-by :Salary emps)))]
(println e))) | 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 = true
case r == sep:
tokens = append(tokens, string(runes))
runes = runes[:0]
}
}
tokens = append(tokens, string(runes))
if inEscape {
err = errors.New("invalid terminal escape")
}
return tokens, err
}
func main() {
const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
const separator = '|'
const escape = '^'
fmt.Printf("Input: %q\n", sample)
tokens, err := TokenizeString(sample, separator, escape)
if err != nil {
fmt.Println("error:", err)
} else {
fmt.Printf("Tokens:%q\n", tokens)
}
} | 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.8343333301, 0.0538864941],
[-1.7011985145, -0.1263820964, 0.4776976918],
[-0.4319462812, 1.4104420482, 0.7886291537],
[ 0.2178372997, -0.9499557344, 0.0357871187],
[-0.6294854565, -1.3078893852, 0.7653357688],
[ 1.7952608455, 0.6281269104, 0.2727652452],
[ 1.4168575317, 1.0683357171, 1.1016025378],
[ 1.4637371396, 0.9463877418, 1.1846214562],
[-0.5263668798, 1.7315156631, 1.4428514068],
[-1.2197352481, 0.9144146579, 1.0727263474],
[-0.1389358881, 0.1092805780, 0.7350208828],
[ 1.5293954595, 0.0030278255, 1.2472867347],
[-0.5258728625, 1.3782633069, 1.3495508831],
[-0.1403562064, 0.2437382535, 1.3804956588],
[ 0.8055826339, -0.0482092025, 0.3327165165],
[-0.6311979224, 0.7184578971, 0.2491045282],
[ 1.4685857879, -0.8347049536, 1.3670667538],
[-0.6855727502, 1.6465021616, 1.0593087096],
[ 0.0152957411, 0.0638919221, 0.9771215985],
]
def minmax_circle(circles)
xmin = circles.map {|xc, yc, radius| xc - radius}.min
xmax = circles.map {|xc, yc, radius| xc + radius}.max
ymin = circles.map {|xc, yc, radius| yc - radius}.min
ymax = circles.map {|xc, yc, radius| yc + radius}.max
[xmin, xmax, ymin, ymax]
end
def select_circle(circles)
circles = circles.sort_by{|cx,cy,r| -r}
size = circles.size
select = [*0...size]
for i in 0...size-1
xi,yi,ri = circles[i].to_a
for j in i+1...size
xj,yj,rj = circles[j].to_a
select -= [j] if (xi-xj)**2 + (yi-yj)**2 <= (ri-rj)**2
end
end
circles.values_at(*select)
end
circles = select_circle(circles) | 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"; last; }
}
for (reverse @{primes(1e6)}) {
if (isrtrunc($_)) { print "rtrunc: $_\n"; last; }
} | 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)
r = pow(n, (q + 1)
t = pow(n, q, p)
m = s
t2 = 0
while (t - 1)% p != 0:
t2 = (t * t)% p
for i in range(1, m):
if (t2 - 1)% p == 0:
break
t2 = (t2 * t2)% p
b = pow(c, 1 << (m - i - 1), p)
r = (r * b)% p
c = (b * b)% p
t = (t * c)% p
m = i
return r
if __name__ == '__main__':
ttest = [(10, 13), (56, 101), (1030, 10009), (44402, 100049),
(665820697, 1000000009), (881398088036, 1000000000039),
(41660815127637347468140745042827704103445750172002, 10**50 + 577)]
for n, p in ttest:
r = tonelli(n, p)
assert (r * r - n)% p == 0
print(% (n, p))
print(% (r, p - r)) | 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 == esc && ch /= sep = (0, [ch]:r:rs)
| otherwise = (0, (ch:r):rs) | 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
[[ p -eq POS ]] && printf "$BOLD$GREEN"
[[ ${B[p]} = e ]] && printf "$UL$DIM%d$OFF" $p || printf "$UL%s$OFF" ${B[p]}
{ [[ p%3 -lt 2 ]] && printf "$UL | $OFF"; } || printf "\n"
done
};
function win(){
local ME=$1; local -i p=$2
[[ ${B[p/3*3]} = $ME && ${B[p/3*3+1]} = $ME && ${B[p/3*3+2]} = $ME ]] && return 0
[[ ${B[p]} = $ME && ${B[(p+3)%9]} = $ME && ${B[(p+6)%9]} = $ME ]] && return 0
[[ ${B[4]} != $ME ]] && return 1
[[ p%4 -eq 0 && ${B[0]} = $ME && ${B[8]} = $ME ]] && return 0
[[ p%4 -eq 2 || p -eq 4 ]] && [[ ${B[2]} = $ME && ${B[6]} = $ME ]]
};
function bestMove(){
local ME=$1 OP=$2; local -i o s p
local -ia S=( -9 -9 -9 -9 -9 -9 -9 -9 -9 )
local -a SB
[[ ${B[*]//[!e]} = "" ]] && return 9
SB=( ${B[*]} )
for p in 0 1 2 3 4 5 6 7 8; do
[[ ${B[p]} != e ]] && continue
B[p]=$ME
win $ME $p && { S[p]=2; B=( ${SB[*]} ); return $p; }
bestMove $OP $ME; o=$?
[[ o -le 8 ]] && { B[o]=$OP; win $OP $o; s=$?; }
S[p]=${s:-1}
B=( ${SB[*]} )
done
local -i best=-1; local -ia MOV=()
for p in 0 1 2 3 4 5 6 7 8; do
[[ S[p] -lt 0 ]] && continue
[[ S[p] -eq S[best] ]] && { MOV+=(p); best=p; }
[[ S[p] -gt S[best] ]] && { MOV=(p); best=p; }
done
return ${MOV[ RANDOM%${
};
function getMove(){
[[ $ME = X ]] && { bestMove $ME $OP; return $?; }
read -p "O move: " -n 1; printf "\n"; return $REPLY
};
function turn(){
local -i p; local ME=$1 OP=$2
getMove; p=$?; [[ p -gt 8 ]] && { printf "Draw!\n"; show; return 1; }
B[p]=$ME; printf "%s moves%d\n" $ME $p
win $ME $p && { printf "%s wins!\n" $ME; show $p; [[ $ME = X ]] && return 2; return 0; }
[[ ${B[*]//[!e]} = "" ]] && { printf "Draw!\n"; show; return 1; }
show $p; turn $OP $ME
};
printf "Bic Bash Bow\n"
show; [[ RANDOM%2 -eq 0 ]] && { turn O X; exit $?; } || turn X O | 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(tokenizeString(sample, separator, escape));
} catch (Exception e) {
System.out.println(e);
}
}
public static List<String> tokenizeString(String s, char sep, char escape)
throws Exception {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
boolean inEscape = false;
for (char c : s.toCharArray()) {
if (inEscape) {
inEscape = false;
} else if (c == escape) {
inEscape = true;
continue;
} else if (c == sep) {
tokens.add(sb.toString());
sb.setLength(0);
continue;
}
sb.append(c);
}
if (inEscape)
throw new Exception("Invalid terminal escape");
tokens.add(sb.toString());
return tokens;
}
} | 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 dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys `
func main() {
g, in, err := parseLibComp(data)
if err != nil {
fmt.Println(err)
return
}
order, cyclic := topSortKahn(g, in)
if cyclic != nil {
fmt.Println("Cyclic:", cyclic)
return
}
fmt.Println("Order:", order)
}
type graph map[string][]string
type inDegree map[string]int | 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 rotateLeft(l: List[Int]) =
l match {
case Nil => List()
case x :: xs => xs ::: List(x)
}
if (i >= n) acc
else {
if (n == 1) acc.max(flips(l))
else {
val split = l.splitAt(n)
fannkuchen(rotateLeft(split._1) ::: split._2, n, i + 1, fannkuchen(l, n - 1, 0, acc))
}
}
} | 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,'^','|'), i=0; i<a.length; i+=1) document.write(i, ': ', a[i], '<br>') | 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")
, ("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")
, ("dw06", "dw06 ieee dware")
, ("dw07", "ieee dware")
, ("dware", "ieee dware")
, ("gtech", "ieee gtech")
, ("ramlib", "std ieee")
, ("std_cell_lib", "ieee std_cell_lib")
, ("synopsys", [])
]
toposort :: [(String, String)] -> [String]
toposort xs
| (not . null) cycleDetect =
error $ "Dependency cycle detected for libs " ++ show cycleDetect
| otherwise = foldl makePrecede [] dB
where
dB = (\(x, y) -> (x, y \\ x)) . bimap return words <$> xs
makePrecede ts ([x], xs) =
nub $
case elemIndex x ts of
Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts
_ -> ts ++ xs ++ [x]
cycleDetect =
filter ((> 1) . length) $
(\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>
combs 2 dB
main :: IO ()
main = print $ toposort depLibs | 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, tsi.tv_sec);
long elaps_ns = tsf.tv_nsec - tsi.tv_nsec;
return elaps_s + ((double)elaps_ns) / 1.0e9;
}
int main()
{
printf(, time_it(identity, 4));
printf(, time_it(sum, 4));
return 0;
} | 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.toString();
sb1.append(sb2);
sb2.append(tmp);
}
System.out.println(sb1);
}
} | 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) =%f\n", d, math.Cos(d*math.Pi/180))
fmt.Printf("cos(%9.6f rad) =%f\n", r, math.Cos(r))
fmt.Printf("tan(%9.6f deg) =%f\n", d, math.Tan(d*math.Pi/180))
fmt.Printf("tan(%9.6f rad) =%f\n", r, math.Tan(r))
fmt.Printf("asin(%f) =%9.6f deg\n", s, math.Asin(s)*180/math.Pi)
fmt.Printf("asin(%f) =%9.6f rad\n", s, math.Asin(s))
fmt.Printf("acos(%f) =%9.6f deg\n", c, math.Acos(c)*180/math.Pi)
fmt.Printf("acos(%f) =%9.6f rad\n", c, math.Acos(c))
fmt.Printf("atan(%f) =%9.6f deg\n", t, math.Atan(t)*180/math.Pi)
fmt.Printf("atan(%f) =%9.6f rad\n", t, math.Atan(t))
} | 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 $limit (100, 1000, 10000) {
printf "Count of primes <= $limit:%d\n", scalar grep {$_ == $[$_] + 1} 0..$limit;
} | 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.tan(radians)} == tan(45\u00B0) = ${Math.tan(d2r(degrees))}"
println "asin(\u221A2/2) = ${Math.asin(2**(-0.5))} == asin(\u221A2/2)\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\u00B0"
println "acos(\u221A2/2) = ${Math.acos(2**(-0.5))} == acos(\u221A2/2)\u00B0 = ${r2d(Math.acos(2**(-0.5)))}\u00B0"
println "atan(1) = ${Math.atan(1)} == atan(1)\u00B0 = ${r2d(Math.atan(1))}\u00B0" | 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 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>> | 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];
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1];
return 0;
}
void showboard()
{
const char *t = ;
int i, j;
for (i = 0; i < 3; i++, putchar('\n'))
for (j = 0; j < 3; j++)
printf(, t[ b[i][j] + 1 ]);
printf();
}
int best_i, best_j;
int test_move(int val, int depth)
{
int i, j, score;
int best = -1, changed = 0;
if ((score = check_winner())) return (score == val) ? 1 : -1;
for_ij {
if (b[i][j]) continue;
changed = b[i][j] = val;
score = -test_move(-val, depth + 1);
b[i][j] = 0;
if (score <= best) continue;
if (!depth) {
best_i = i;
best_j = j;
}
best = score;
}
return changed ? best : 0;
}
const char* game(int user)
{
int i, j, k, move, win = 0;
for_ij b[i][j] = 0;
printf();
printf();
for (k = 0; k < 9; k++, user = !user) {
while(user) {
printf();
if (!scanf(, &move)) {
scanf();
continue;
}
if (--move < 0 || move >= 9) continue;
if (b[i = move / 3][j = move % 3]) continue;
b[i][j] = 1;
break;
}
if (!user) {
if (!k) {
best_i = rand() % 3;
best_j = rand() % 3;
} else
test_move(-1, 0);
b[best_i][best_j] = -1;
printf(, best_i * 3 + best_j + 1);
}
showboard();
if ((win = check_winner()))
return win == 1 ? : ;
}
return ;
}
int main()
{
int first = 0;
while (1) printf(, game(first = !first));
return 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 .. "1"
end
end
self.sequence = self.sequence .. newBlock
end
for i = 1, 5 do
ThueMorse:show()
ThueMorse:addBlock()
end | 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
end
elseif ch == sep then
if escaped then
word = word .. ch
escaped = false
else
table.insert(strList, word)
word = ""
end
else
escaped = false
word = word .. ch
end
end
table.insert(strList, word)
return strList
end
local testStr = "one^|uno||three^^^^|four^^^|^cuatro|"
local testSep, testEsc = "|", "^"
for k, v in pairs(tokenise(testStr, testSep, testEsc)) do
print(k, v)
end | 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 += @tape if $pos < 0;
die "bad init position" if $pos >= @tape || $pos < 0;
step: while (1) {
print "$st\t";
for (0 .. $
my $v = $tape[$_];
print $_ == $pos ? "[$v]" : " $v ";
}
print "\n";
last if $st eq $halt;
for (@rules) {
my ($s0, $v0, $v1, $dir, $s1) = @$_;
next unless $s0 eq $st and $tape[$pos] eq $v0;
$tape[$pos] = $v1;
if ($dir eq 'left') {
if ($pos == 0) { unshift @tape, $blank}
else { $pos-- }
} elsif ($dir eq 'right') {
push @tape, $blank if ++$pos >= @tape
}
$st = $s1;
next step;
}
die "no matching rules";
}
}
print "incr machine\n";
run_utm halt=>'qf',
state=>'q0',
tape=>[1,1,1],
blank=>'B',
rules=>[[qw/q0 1 1 right q0/],
[qw/q0 B 1 stay qf/]];
print "\nbusy beaver\n";
run_utm halt=>'halt',
state=>'a',
blank=>'0',
rules=>[[qw/a 0 1 right b/],
[qw/a 1 1 left c/],
[qw/b 0 1 left a/],
[qw/b 1 1 right b/],
[qw/c 0 1 left b/],
[qw/c 1 1 stay halt/]];
print "\nsorting test\n";
run_utm halt=>'STOP',
state=>'A',
blank=>'0',
tape=>[qw/2 2 2 1 2 2 1 2 1 2 1 2 1 2/],
rules=>[[qw/A 1 1 right A/],
[qw/A 2 3 right B/],
[qw/A 0 0 left E/],
[qw/B 1 1 right B/],
[qw/B 2 2 right B/],
[qw/B 0 0 left C/],
[qw/C 1 2 left D/],
[qw/C 2 2 left C/],
[qw/C 3 2 left E/],
[qw/D 1 1 left D/],
[qw/D 2 2 left D/],
[qw/D 3 1 right A/],
[qw/E 1 1 left E/],
[qw/E 0 0 right STOP/]]; | 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)
, asin 0.5
, toDegrees (asin 0.5)
, acos 0.5
, toDegrees (acos 0.5)
, atan 0.5
, toDegrees (atan 0.5)
] | 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'
primelist = [str(x) for x in primes(n)[::-1]]
primeset = set(primelist)
for n in primelist:
alltruncs = set(n[i:] for i in range(len(n)))
if alltruncs.issubset(primeset):
truncateleft = int(n)
break
for n in primelist:
alltruncs = set([n[:i+1] for i in range(len(n))])
if alltruncs.issubset(primeset):
truncateright = int(n)
break
return truncateleft, truncateright
print(truncatableprime(maxprime)) | 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}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},
{3, 1}, {3, 10}, {3, 11},
{4, 1}, {4, 10},
{5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},
{6, 1}, {6, 3}, {6, 10}, {6, 11},
{7, 1}, {7, 10},
{8, 1}, {8, 10},
{9, 1}, {9, 10},
{10, 1},
{11, 1},
{12, 0}, {12, 1},
{13, 1}
});
System.out.println("Topologically sorted order: ");
System.out.println(g.topoSort());
}
}
class Graph {
String[] vertices;
boolean[][] adjacency;
int numVertices;
public Graph(String s, int[][] edges) {
vertices = s.split(",");
numVertices = vertices.length;
adjacency = new boolean[numVertices][numVertices];
for (int[] edge : edges)
adjacency[edge[0]][edge[1]] = true;
}
List<String> topoSort() {
List<String> result = new ArrayList<>();
List<Integer> todo = new LinkedList<>();
for (int i = 0; i < numVertices; i++)
todo.add(i);
try {
outer:
while (!todo.isEmpty()) {
for (Integer r : todo) {
if (!hasDependency(r, todo)) {
todo.remove(r);
result.add(vertices[r]); | 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
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys`; | 110Topological sort
| 10javascript
| 3n8z0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.