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" "sort" )
863Faces from a mesh
0go
qzzxz
import Data.List (find, delete, (\\)) import Control.Applicative ((<|>)) newtype Perimeter a = Perimeter [a] deriving Show instance Eq a => Eq (Perimeter a) where Perimeter p1 == Perimeter p2 = null (p1 \\ p2) && ((p1 `elem` zipWith const (iterate rotate p2) p1) || Perimeter p1 == Perimeter (reverse p2)) rotate lst = zipWith const (tail (cycle lst)) lst toEdges :: Ord a => Perimeter a -> Maybe (Edges a) toEdges (Perimeter ps) | allDifferent ps = Just . Edges $ zipWith ord ps (tail (cycle ps)) | otherwise = Nothing where ord a b = if a < b then (a, b) else (b, a) allDifferent [] = True allDifferent (x:xs) = all (x /=) xs && allDifferent xs newtype Edges a = Edges [(a, a)] deriving Show instance Eq a => Eq (Edges a) where e1 == e2 = toPerimeter e1 == toPerimeter e2 toPerimeter :: Eq a => Edges a -> Maybe (Perimeter a) toPerimeter (Edges ((a, b):es)) = Perimeter . (a:) <$> go b es where go x rs | x == a = return [] | otherwise = do p <- find ((x ==) . fst) rs <|> find ((x ==) . snd) rs let next = if fst p == x then snd p else fst p (x:) <$> go next (delete p rs)
863Faces from a mesh
8haskell
mrryf
(1 to 100).filter(_ % 2 == 0)
853Filter
16scala
edlab
use strict; use warnings; use feature 'say'; use Set::Scalar; use Set::Bag; use Storable qw(dclone); sub show { my($pts) = @_; my $p='( '; $p .= '(' . join(' ',@$_) . ') ' for @$pts; $p.')' } sub check_equivalence { my($a, $b) = @_; Set::Scalar->new(@$a) == Set::Scalar->new(@$b) } sub edge_to_periphery { my $a = dclone \@_; my $bag_a = Set::Bag->new; for my $p (@$a) { $bag_a->insert( @$p[0] => 1); $bag_a->insert( @$p[1] => 1); } 2 != @$bag_a{$_} and return 0 for keys %$bag_a; my $b = shift @$a; while ($ for my $k (0..$ my $v = @$a[$k]; if (@$v[0] == @$b[-1]) { push @$b, @$v[1]; splice(@$a,$k,1); last } elsif (@$v[1] == @$b[-1]) { push @$b, @$v[0]; splice(@$a,$k,1); last } } } @$b; } say 'Perimeter format equality checks:'; for ([[8, 1, 3], [1, 3, 8]], [[18, 8, 14, 10, 12, 17, 19], [8, 14, 10, 12, 17, 19, 18]]) { my($a, $b) = @$_; say '(' . join(', ', @$a) . ') equivalent to (' . join(', ', @$b) . ')? ', check_equivalence($a, $b) ? 'True' : 'False'; } say "\nEdge to perimeter format translations:"; for ([[1, 11], [7, 11], [1, 7]], [[11, 23], [1, 17], [17, 23], [1, 11]], [[8, 14], [17, 19], [10, 12], [10, 14], [12, 17], [8, 18], [18, 19]], [[1, 3], [9, 11], [3, 11], [1, 11]]) { say show($_) . ' ==> (' . (join ' ', edge_to_periphery(@$_) or 'Invalid edge format') . ')' }
863Faces from a mesh
2perl
4aa5d
package main import ( "fmt" "math" ) type float float64 func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) } func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x =%2.0f e =%0.0f | ", x, e) fmt.Printf("%s =%4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s =%4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s =%4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s =%4.0f\n", ops[3], -(x.p(e))) } } }
864Exponentiation with infix operators in (or operating on) the base
0go
6453p
use strict; use warnings; use feature qw(say); for my $i (1..100) { say $i % 15 == 0 ? "FizzBuzz" : $i % 3 == 0 ? "Fizz" : $i % 5 == 0 ? "Buzz" : $i; }
835FizzBuzz
2perl
boak4
main = do print [-5^2,-(5)^2,(-5)^2,-(5^2)] print [-5^^2,-(5)^^2,(-5)^^2,-(5^^2)] print [-5**2,-(5)**2,(-5)**2,-(5**2)] print [-5^3,-(5)^3,(-5)^3,-(5^3)] print [-5^^3,-(5)^^3,(-5)^^3,-(5^^3)] print [-5**3,-(5)**3,(-5)**3,-(5**3)]
864Exponentiation with infix operators in (or operating on) the base
8haskell
jqx7g
def perim_equal(p1, p2): if len(p1) != len(p2) or set(p1) != set(p2): return False if any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))): return True p2 = p2[::-1] return any(p2 == (p1[n:] + p1[:n]) for n in range(len(p1))) def edge_to_periphery(e): edges = sorted(e) p = list(edges.pop(0)) if edges else [] last = p[-1] if p else None while edges: for n, (i, j) in enumerate(edges): if i == last: p.append(j) last = j edges.pop(n) break elif j == last: p.append(i) last = i edges.pop(n) break else: return return p[:-1] if __name__ == '__main__': print('Perimeter format equality checks:') for eq_check in [ { 'Q': (8, 1, 3), 'R': (1, 3, 8)}, { 'U': (18, 8, 14, 10, 12, 17, 19), 'V': (8, 14, 10, 12, 17, 19, 18)} ]: (n1, p1), (n2, p2) = eq_check.items() eq = '==' if perim_equal(p1, p2) else '!=' print(' ', n1, eq, n2) print('\nEdge to perimeter format translations:') edge_d = { 'E': {(1, 11), (7, 11), (1, 7)}, 'F': {(11, 23), (1, 17), (17, 23), (1, 11)}, 'G': {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)}, 'H': {(1, 3), (9, 11), (3, 11), (1, 11)} } for name, edges in edge_d.items(): print(f)
863Faces from a mesh
3python
gee4h
mathtype = math.type or type
864Exponentiation with infix operators in (or operating on) the base
1lua
cj792
int main() { double inf = 1/0.0; double minus_inf = -1/0.0; double minus_zero = -1/ inf ; double nan = 0.0/0.0; printf(,inf); printf(,minus_inf); printf(,minus_zero); printf(,nan); printf(,inf + 2.0); printf(,inf - 10.1); printf(,inf + minus_inf); printf(,0.0 * inf); printf(,1.0/minus_zero); printf(,nan + 1.0); printf(,nan + nan); printf(,nan == nan ? : ); printf(,0.0 == minus_zero ? : ); return 0; }
865Extreme floating point values
5c
wfnec
package main import ( "fmt" "math/rand" "strconv" "strings" "time" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func genFactBaseNums(size int, countOnly bool) ([][]int, int) { var results [][]int count := 0 for n := 0; ; n++ { radix := 2 var res []int = nil if !countOnly { res = make([]int, size) } k := n for k > 0 { div := k / radix rem := k % radix if !countOnly { if radix <= size+1 { res[size-radix+1] = rem } } k = div radix++ } if radix > size+2 { break } count++ if !countOnly { results = append(results, res) } } return results, count } func mapToPerms(factNums [][]int) [][]int { var perms [][]int psize := len(factNums[0]) + 1 start := make([]int, psize) for i := 0; i < psize; i++ { start[i] = i } for _, fn := range factNums { perm := make([]int, psize) copy(perm, start) for m := 0; m < len(fn); m++ { g := fn[m] if g == 0 { continue } first := m last := m + g for i := 1; i <= g; i++ { temp := perm[first] for j := first + 1; j <= last; j++ { perm[j-1] = perm[j] } perm[last] = temp } } perms = append(perms, perm) } return perms } func join(is []int, sep string) string { ss := make([]string, len(is)) for i := 0; i < len(is); i++ { ss[i] = strconv.Itoa(is[i]) } return strings.Join(ss, sep) } func undot(s string) []int { ss := strings.Split(s, ".") is := make([]int, len(ss)) for i := 0; i < len(ss); i++ { is[i], _ = strconv.Atoi(ss[i]) } return is } func main() { rand.Seed(time.Now().UnixNano())
866Factorial base numbers indexing permutations of a collection
0go
wfieg
(def neg-inf (/ -1.0 0.0)) (def inf (/ 1.0 0.0)) (def nan (/ 0.0 0.0)) (def neg-zero (/ -2.0 Double/POSITIVE_INFINITY)) (println " Negative inf: " neg-inf) (println " Positive inf: " inf) (println " NaN: " nan) (println " Negative 0: " neg-zero) (println " inf + -inf: " (+ inf neg-inf)) (println " NaN == NaN: " (= Double/NaN Double/NaN)) (println "NaN equals NaN: " (.equals Double/NaN Double/NaN))
865Extreme floating point values
6clojure
8y305
import Data.List (unfoldr, intercalate) newtype Fact = Fact [Int] fact :: [Int] -> Fact fact = Fact . zipWith min [0..] . reverse instance Show Fact where show (Fact ds) = intercalate "." $ show <$> reverse ds toFact :: Integer -> Fact toFact 0 = Fact [0] toFact n = Fact $ unfoldr f (1, n) where f (b, 0) = Nothing f (b, n) = let (q, r) = n `divMod` b in Just (fromIntegral r, (b+1, q)) fromFact :: Fact -> Integer fromFact (Fact ds) = foldr f 0 $ zip [1..] ds where f (b, d) r = r * b + fromIntegral d
866Factorial base numbers indexing permutations of a collection
8haskell
64v3k
<?php for ($i = 1; $i <= 100; $i++) { if (!($i % 15)) echo ; else if (!($i % 3)) echo ; else if (!($i % 5)) echo ; else echo ; } ?>
835FizzBuzz
12php
6g93g
int main() { int n, b, d; unsigned long long i, j, sum, fact[12]; fact[0] = 1; for (n = 1; n < 12; ++n) { fact[n] = fact[n-1] * n; } for (b = 9; b <= 12; ++b) { printf(, b); for (i = 1; i < 1500000; ++i) { sum = 0; j = i; while (j > 0) { d = j % b; sum += fact[d]; j /= b; } if (sum == i) printf(, i); } printf(); } return 0; }
867Factorions
5c
lhgcy
use strict; use warnings; use Sub::Infix; BEGIN { *e = infix { $_[0] ** $_[1] } }; my @eqns = ('1 + -$xOP$p', '1 + (-$x)OP$p', '1 + (-($x)OP$p)', '(1 + -$x)OP$p', '1 + -($xOP$p)'); for my $op ('**', '/e/', '|e|') { for ( [-5, 2], [-5, 3], [5, 2], [5, 3] ) { my( $x, $p, $eqn ) = @$_; printf 'x:%2d p:%2d |', $x, $p; $eqn = s/OP/$op/gr and printf '%17s%4d |', $eqn, eval $eqn for @eqns; print "\n"; } print "\n"; }
864Exponentiation with infix operators in (or operating on) the base
2perl
wfde6
use strict; use warnings; use feature 'say'; sub fpermute { my($f,@a) = @_; my @f = split /\./, $f; for (0..$ my @b = @a[$_ .. $_+$f[$_]]; unshift @b, splice @b, $ @a[$_ .. $_+$f[$_]] = @b; } join '', @a; } sub base { my($n) = @_; my @digits; push(@digits, int $n/$_) and $n = $n % $_ for <6 2 1>; join '.', @digits; } say 'Generate table'; for (0..23) { my $x = base($_); say $x . ' -> ' . fpermute($x, <0 1 2 3>) } say "\nGenerate the given task shuffles"; my @omega = qw<A K Q J 10 9 8 7 6 5 4 3 2 A K Q J 10 9 8 7 6 5 4 3 2 A K Q J 10 9 8 7 6 5 4 3 2 A K Q J 10 9 8 7 6 5 4 3 2>; my @books = ( '39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0', '51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1' ); say "Original deck:"; say join '', @omega; say "\n$_\n" . fpermute($_,@omega) for @books; say "\nGenerate a random shuffle"; say my $shoe = join '.', map { int rand($_) } reverse 0..$ say fpermute($shoe,@omega);
866Factorial base numbers indexing permutations of a collection
2perl
uphvr
expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p)) x <- c(-5, -5, 5, 5) p <- c(2, 3, 2, 3) output <- data.frame(x, p, setNames(lapply(expressions, eval), sapply(expressions, deparse)), check.names = FALSE) print(output, row.names = FALSE)
864Exponentiation with infix operators in (or operating on) the base
13r
1iopn
--Create the original array (table CREATE TABLE DECLARE @n INT SET @n=1 while @n<=10 BEGIN INSERT INTO --Select the subset that are even into the new array (table SELECT v INTO -- Show SELECT * FROM -- Clean up so you can edit and repeat: DROP TABLE DROP TABLE
853Filter
19sql
qzuxb
nums = [-5, 5] pows = [2, 3] nums.product(pows) do |x, p| puts end
864Exponentiation with infix operators in (or operating on) the base
14ruby
s3zqw
import math def apply_perm(omega,fbn): for m in range(len(fbn)): g = fbn[m] if g > 0: new_first = omega[m+g] omega[m+1:m+g+1] = omega[m:m+g] omega[m] = new_first return omega def int_to_fbn(i): current = i divisor = 2 new_fbn = [] while current > 0: remainder = current% divisor current = current new_fbn.append(remainder) divisor += 1 return list(reversed(new_fbn)) def leading_zeros(l,n): if len(l) < n: return(([0] * (n - len(l))) + l) else: return l def get_fbn(n): max = math.factorial(n) for i in range(max): current = i divisor = 1 new_fbn = int_to_fbn(i) yield leading_zeros(new_fbn,n-1) def print_write(f, line): print(line) f.write(str(line)+'\n') def dot_format(l): if len(l) < 1: return dot_string = str(l[0]) for e in l[1:]: dot_string += +str(e) return dot_string def str_format(l): if len(l) < 1: return new_string = for e in l: new_string += str(e) return new_string with open(, , encoding=) as f: f.write() omega=[0,1,2,3] four_list = get_fbn(4) for l in four_list: print_write(f,dot_format(l)+' -> '+str_format(apply_perm(omega[:],l))) print_write(f,) num_permutations = 0 for p in get_fbn(11): num_permutations += 1 if num_permutations% 1000000 == 0: print_write(f,+str(num_permutations)) print_write(f,) print_write(f,+str(num_permutations)) print_write(f,+str(math.factorial(11))) print_write(f,) shoe = [] for suit in [u,u,u,u]: for value in ['A','K','Q','J','10','9','8','7','6','5','4','3','2']: shoe.append(value+suit) print_write(f,str_format(shoe)) p1 = [39,49,7,47,29,30,2,12,10,3,29,37,33,17,12,31,29,34,17,25,2,4,25,4,1,14,20,6,21,18,1,1,1,4,0,5,15,12,4,3,10,10,9,1,6,5,5,3,0,0,0] p2 = [51,48,16,22,3,0,19,34,29,1,36,30,12,32,12,29,30,26,14,21,8,12,1,3,10,4,7,17,6,21,8,12,15,15,13,15,7,3,12,11,9,5,5,6,6,3,4,0,3,2,1] print_write(f,) print_write(f,dot_format(p1)) print_write(f,) print_write(f,str_format(apply_perm(shoe[:],p1))) print_write(f,) print_write(f,dot_format(p2)) print_write(f,) print_write(f,str_format(apply_perm(shoe[:],p2))) import random max = math.factorial(52) random_int = random.randint(0, max-1) myperm = leading_zeros(int_to_fbn(random_int),51) print(len(myperm)) print_write(f,) print_write(f,dot_format(myperm)) print_write(f,) print_write(f,str_format(apply_perm(shoe[:],myperm))) f.write()
866Factorial base numbers indexing permutations of a collection
3python
51kux
from itertools import product xx = '-5 +5'.split() pp = '2 3'.split() texts = '-x**p -(x)**p (-x)**p -(x**p)'.split() print('Integer variable exponentiation') for x, p in product(xx, pp): print(f' x,p = {x:2},{p}; ', end=' ') x, p = int(x), int(p) print('; '.join(f for t in texts)) print('\nBonus integer literal exponentiation') X, P = 'xp' xx.insert(0, ' 5') texts.insert(0, 'x**p') for x, p in product(xx, pp): texts2 = [t.replace(X, x).replace(P, p) for t in texts] print(' ', '; '.join(f for t2 in texts2))
864Exponentiation with infix operators in (or operating on) the base
3python
xtfwr
let numbers = [1,2,3,4,5,6] let even_numbers = numbers.filter { $0% 2 == 0 } println(even_numbers)
853Filter
17swift
k06hx
sub factors { my($n) = @_; return grep { $n % $_ == 0 }(1 .. $n); } print join ' ',factors(64), "\n";
861Factors of an integer
2perl
xt3w8
package main import ( "fmt" "math" ) func main() {
865Extreme floating point values
0go
cjr9g
package main import ( "fmt" "strconv" ) func main() {
867Factorions
0go
xtiwf
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard) factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b)) main :: IO () main = mapM_ (uncurry (printf "Factorions for base%2d:%s\n") . (\(a, b) -> (b, result a b))) [(3,9), (4,10), (5,11), (2,12)] where factorions b = filter (factorion b) [1..] result n = show . take n . factorions
867Factorions
8haskell
ygv66
def negInf = -1.0d / 0.0d;
865Extreme floating point values
7groovy
35vzd
main = do let inf = 1/0 let minus_inf = -1/0 let minus_zero = -1/inf let nan = 0/0 putStrLn ("Positive infinity = "++(show inf)) putStrLn ("Negative infinity = "++(show minus_inf)) putStrLn ("Negative zero = "++(show minus_zero)) putStrLn ("Not a number = "++(show nan)) putStrLn ("inf + 2.0 = "++(show (inf+2.0))) putStrLn ("inf - 10 = "++(show (inf-10))) putStrLn ("inf - inf = "++(show (inf-inf))) putStrLn ("inf * 0 = "++(show (inf * 0))) putStrLn ("nan + 1.0= "++(show (nan+1.0))) putStrLn ("nan + nan = "++(show (nan + nan))) putStrLn ("nan == nan = "++(show (nan == nan))) putStrLn ("0.0 == - 0.0 = "++(show (0.0 == minus_zero))) putStrLn ("inf == inf = "++(show (inf == inf)))
865Extreme floating point values
8haskell
po0bt
public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); } public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; }
867Factorions
9java
dlyn9
switch(((firsttest)?0:2)+((secondtest)?0:1)) {\ case 0: bothtrue; break;\ case 1: firsttrue; break;\ case 2: secondtrue; break;\ case 3: bothfalse; break;\ }
868Extend your language
5c
zu9tx
int field[CHUNK_BYTES]; typedef unsigned uint; typedef struct { uint *e; uint cap, len; } uarray; uarray primes, offset; void push(uarray *a, uint n) { if (a->len >= a->cap) { if (!(a->cap *= 2)) a->cap = 16; a->e = realloc(a->e, sizeof(uint) * a->cap); } a->e[a->len++] = n; } uint low; void init(void) { uint p, q; unsigned char f[1<<16]; memset(f, 0, sizeof(f)); push(&primes, 2); push(&offset, 0); for (p = 3; p < 1<<16; p += 2) { if (f[p]) continue; for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1; push(&primes, p); push(&offset, q); } low = 1<<16; } void sieve(void) { uint i, p, q, hi, ptop; if (!low) init(); memset(field, 0, sizeof(field)); hi = low + CHUNK_SIZE; ptop = sqrt(hi) * 2 + 1; for (i = 1; (p = primes.e[i]*2) < ptop; i++) { for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p) SET(q); offset.e[i] = q + low; } for (p = 1; p < CHUNK_SIZE; p += 2) if (!GET(p)) push(&primes, low + p); low = hi; } int main(void) { uint i, p, c; while (primes.len < 20) sieve(); printf(); for (i = 0; i < 20; i++) printf(, primes.e[i]); putchar('\n'); while (primes.e[primes.len-1] < 150) sieve(); printf(); for (i = 0; i < primes.len; i++) { if ((p = primes.e[i]) >= 100 && p < 150) printf(, primes.e[i]); } putchar('\n'); while (primes.e[primes.len-1] < 8000) sieve(); for (i = c = 0; i < primes.len; i++) if ((p = primes.e[i]) >= 7700 && p < 8000) c++; printf(, c); for (c = 10; c <= 100000000; c *= 10) { while (primes.len < c) sieve(); printf(, c, primes.e[c-1]); } return 0; }
869Extensible prime generator
5c
64c32
function GetFactors($n){ $factors = array(1, $n); for($i = 2; $i * $i <= $n; $i++){ if($n % $i == 0){ $factors[] = $i; if($i * $i != $n) $factors[] = $n/$i; } } sort($factors); return $factors; }
861Factors of an integer
12php
2kpl4
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0;
865Extreme floating point values
9java
rwag0
(defmacro if2 [[cond1 cond2] bothTrue firstTrue secondTrue else] `(let [cond1# ~cond1 cond2# ~cond2] (if cond1# (if cond2# ~bothTrue ~firstTrue) (if cond2# ~secondTrue ~else))))
868Extend your language
6clojure
97uma
use strict; use warnings; use ntheory qw/factorial todigits/; my $limit = 1500000; for my $b (9 .. 12) { print "Factorions in base $b:\n"; $_ == factorial($_) and print "$_ " for 0..$b-1; for my $i (1 .. int $limit/$b) { my $sum; my $prod = $i * $b; for (reverse todigits($i, $b)) { $sum += factorial($_); $sum = 0 && last if $sum > $prod; } next if $sum == 0; ($sum + factorial($_) == $prod + $_) and print $prod+$_ . ' ' for 0..$b-1; } print "\n\n"; }
867Factorions
2perl
51hu2
ns test-project-intellij.core (:gen-class) (:require [clojure.string:as string])) (def primes " The following routine produces a infinite sequence of primes (i.e. can be infinite since the evaluation is lazy in that it only produces values as needed). The method is from clojure primes.clj library which produces primes based upon O'Neill's paper: 'The Genuine Sieve of Eratosthenes'. Produces primes based upon trial division on previously found primes up to (sqrt number), and uses 'wheel' to avoid testing numbers which are divisors of 2, 3, 5, or 7. A full explanation of the method is available at: [https://github.com/stuarthalloway/programming-clojure/pull/12] " (concat [2 3 5 7] (lazy-seq (let [primes-from (fn primes-from [n [f & r]] (if (some #(zero? (rem n %)) (take-while #(<= (* % %) n) primes)) (recur (+ n f) r) (lazy-seq (cons n (primes-from (+ n f) r))))) wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2 6 4 6 8 4 2 4 2 4 8 6 4 6 2 4 6 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])] (primes-from 11 wheel))))) (defn between [lo hi] "Primes between lo and hi value " (->> (take-while #(<= % hi) primes) (filter #(>= % lo)) )) (println "First twenty:" (take 20 primes)) (println "Between 100 and 150:" (between 100 150)) (println "Number between 7,7700 and 8,000:" (count (between 7700 8000))) (println "10,000th prime:" (nth primes (dec 10000))) }
869Extensible prime generator
6clojure
lh5cb
null
865Extreme floating point values
11kotlin
vbh21
local inf=math.huge local minusInf=-math.huge local NaN=0/0 local negativeZeroSorta=-1E-240
865Extreme floating point values
1lua
upkvl
int main() { printf(,pow(pow(5,3),2)); printf(,pow(5,pow(3,2))); return 0; }
870Exponentiation order
5c
lhucy
fact = [1] for n in range(1, 12): fact.append(fact[n-1] * n) for b in range(9, 12+1): print(f) for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j% b fact_sum += fact[d] j = j if fact_sum == i: print(i, end=) print()
867Factorions
3python
4ak5k
import re from typing import Dict from typing import Iterable from typing import List from typing import NamedTuple from typing import Optional from typing import Tuple NOP = 0b000 LDA = 0b001 STA = 0b010 ADD = 0b011 SUB = 0b100 BRZ = 0b101 JMP = 0b110 STP = 0b111 OPCODES = { : NOP, : LDA, : STA, : ADD, : SUB, : BRZ, : JMP, : STP, } RE_INSTRUCTION = re.compile( r r r rf r r r r ) class AssemblySyntaxError(Exception): pass class Instruction(NamedTuple): label: Optional[str] opcode: Optional[str] argument: Optional[str] comment: Optional[str] def parse(assembly: str) -> Tuple[List[Instruction], Dict[str, int]]: instructions: List[Instruction] = [] labels: Dict[str, int] = {} linenum: int = 0 for line in assembly.split(): match = RE_INSTRUCTION.match(line) if not match: raise AssemblySyntaxError(f) instructions.append(Instruction(**match.groupdict())) label = match.group(1) if label: labels[label] = linenum linenum += 1 return instructions, labels def compile(instructions: List[Instruction], labels: Dict[str, int]) -> Iterable[int]: for instruction in instructions: if instruction.argument is None: argument = 0 elif instruction.argument.isnumeric(): argument = int(instruction.argument) else: argument = labels[instruction.argument] if instruction.opcode: yield OPCODES[instruction.opcode] << 5 | argument else: yield argument def run(bytecode: bytes) -> int: accumulator = 0 program_counter = 0 memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))] while program_counter < 32: operation = memory[program_counter] >> 5 argument = memory[program_counter] & 0b11111 program_counter += 1 if operation == NOP: continue elif operation == LDA: accumulator = memory[argument] elif operation == STA: memory[argument] = accumulator elif operation == ADD: accumulator = (accumulator + memory[argument])% 256 elif operation == SUB: accumulator = (accumulator - memory[argument])% 256 elif operation == BRZ: if accumulator == 0: program_counter = argument elif operation == JMP: program_counter = argument elif operation == STP: break else: raise Exception(f) return accumulator SAMPLES = [ , , , , , , , , ] def main() -> None: for sample in SAMPLES: instructions, labels = parse(sample) bytecode = bytes(compile(instructions, labels)) result = run(bytecode) print(result) if __name__ == : main()
871Execute Computer/Zero
3python
poabm
(use 'clojure.math.numeric-tower) (expt (expt 5 3) 2) (expt 5 (expt 3 2)) (reduce expt [5 3 2]) (defn rreduce [f coll] (reduce #(f %2 %) (reverse coll))) (rreduce expt [5 3 2])
870Exponentiation order
6clojure
4a75o
$define VERSION 0.6 link options $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4 record position(row, col) global dir, ip, ram procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug opts := options(argv, , errorproc) \opts[] & verbose := 1 \opts[] & show_help(verbose) \opts[] & debug := 1 ip := position(1,1) dir := DRIGHT ram := list(1, 0) codespace := [] fn := open(argv[1], ) | &input if (fn === &input) & \opts[] then return while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) if /col := find(, codespace[row]) then { ip.row := row ip.col := col } row +:= 1 } if \verbose then { write(, ip.row, , ip.col, ) every write(!codespace) } dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, , dir, , ch, , ord(ch), , , ip.row, , ip.col, , dp, , ram[dp]) } case ch of { : ram[dp] +:= 1 : ram[dp] -:= 1 : resize(dp +:= 1) : dp -:= 1 : writes(char(ram[dp]) | char(0)) : ram[dp] := getche() : { case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } : { case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } : step() : { if ram[dp] = 0 then { step() } } : { push(dirs, dir) push(ips, copy(ip)) } : { if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end procedure resize(elements) until *ram >= elements do put(ram, 0) end procedure show_help(verbose) write(, VERSION) write() write() write() write() write() write() if \verbose then { write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() write() } end
872Execute SNUSP
5c
f2td3
def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1,:*)} == n end (9..12).each do |base| puts end
867Factorions
14ruby
rwpgs
Iterable<int> primesMap() { Iterable<int> oddprms() sync* { yield(3); yield(5);
869Extensible prime generator
18dart
ncziq
object Factorion extends App { private def is_factorion(i: Int, b: Int): Boolean = { var sum = 0L var j = i while (j > 0) { sum += f(j % b) j /= b } sum == i } private val f = Array.ofDim[Long](12) f(0) = 1L (1 until 12).foreach(n => f(n) = f(n - 1) * n) (9 to 12).foreach(b => { print(s"factorions for base $b:") (1 to 1500000).filter(is_factorion(_, b)).foreach(i => print(s" $i")) println }) }
867Factorions
16scala
k0whk
package main import "fmt" import "math" func main() { var a, b, c float64 a = math.Pow(5, math.Pow(3, 2)) b = math.Pow(math.Pow(5, 3), 2) c = math.Pow(5, math.Pow(3, 2)) fmt.Printf("5^3^2 =%.0f\n", a) fmt.Printf("(5^3)^2 =%.0f\n", b) fmt.Printf("5^(3^2) =%.0f\n", c) }
870Exponentiation order
0go
xt0wf
var fact = Array(repeating: 0, count: 12) fact[0] = 1 for n in 1..<12 { fact[n] = fact[n - 1] * n } for b in 9...12 { print("The factorions for base \(b) are:") for i in 1..<1500000 { var sum = 0 var j = i while j > 0 { sum += fact[j% b] j /= b } if sum == i { print("\(i)", terminator: " ") fflush(stdout) } } print("\n") }
867Factorions
17swift
geb49
println(" 5 ** 3 ** 2 == " + 5**3**2) println("(5 ** 3)** 2 == " + (5**3)**2) println(" 5 **(3 ** 2)== " + 5**(3**2))
870Exponentiation order
7groovy
poebo
>:i (^) (^):: (Num a, Integral b) => a -> b -> a infixr 8 ^ >:i (**) class Fractional a => Floating a where ... (**):: a -> a -> a ... infixr 8 ** >:i (^^) (^^):: (Fractional a, Integral b) => a -> b -> a infixr 8 ^^
870Exponentiation order
8haskell
ygc66
jq -n 'pow(pow(5;3);2)' 15625
870Exponentiation order
9java
dlzn9
null
870Exponentiation order
11kotlin
06isf
for i in xrange(1, 101): if i% 15 == 0: print elif i% 3 == 0: print elif i% 5 == 0: print else: print i
835FizzBuzz
3python
piebm
func fib(a int) int { if a < 2 { return a } return fib(a - 1) + fib(a - 2) }
862Fibonacci sequence
0go
hs0jq
use strict; use warnings; my $nzero = -0.0; my $nan = 0 + "nan"; my $pinf = +"inf"; my $ninf = -"inf"; printf "\$nzero =%.1f\n", $nzero; print "\$nan = $nan\n"; print "\$pinf = $pinf\n"; print "\$ninf = $ninf\n\n"; printf "atan2(0, 0) =%g\n", atan2(0, 0); printf "atan2(0, \$nzero) =%g\n", atan2(0, $nzero); printf "sin(\$pinf) =%g\n", sin($pinf); printf "\$pinf / -1 =%g\n", $pinf / -1; printf "\$ninf + 1e100 =%g\n\n", $ninf + 1e100; printf "nan test:%g\n", (1 + 2 * 3 - 4) / (-5.6e7 * $nan); printf "nan == nan?%s\n", ($nan == $nan) ? "yes" : "no"; printf "nan == 42?%s\n", ($nan == 42) ? "yes" : "no";
865Extreme floating point values
2perl
06zs4
# # snusp.icn, A Modular SNUSP interpreter # $define VERSION 0.6 # allow a couple of cli options link options # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4 record position(row, col) global dir, ip, ram procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1 ip := position(1,1) # initial direction dir := DRIGHT # prepare initial memory ram := list(1, 0) # prepare code field codespace := [] fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 } if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) } dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write("!, SKIP, Move forward one step in current direction") write("?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
872Execute SNUSP
0go
jqh7d
print("5^3^2 = " .. 5^3^2) print("(5^3)^2 = " .. (5^3)^2) print("5^(3^2) = " .. 5^(3^2))
870Exponentiation order
1lua
8yn0e
def rFib rFib = { it == 0 ? 0 : it == 1 ? 1 : it > 1 ? rFib(it-1) + rFib(it-2) : rFib(it+2) - rFib(it+1) }
862Fibonacci sequence
7groovy
4ae5f
void runCode(const char *code) { int c_len = strlen(code); int i, bottles; unsigned accumulator=0; for(i=0;i<c_len;i++) { switch(code[i]) { case 'Q': printf(, code); break; case 'H': printf(); break; case '9': bottles = 99; do { printf(, bottles); printf(, bottles); printf(); printf(, --bottles); } while( bottles > 0 ); break; case '+': accumulator++; break; } } };
873Execute HQ9+
5c
060st
# # snusp.icn, A Modular SNUSP interpreter # $define VERSION 0.6 # allow a couple of cli options link options # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4 record position(row, col) global dir, ip, ram procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1 ip := position(1,1) # initial direction dir := DRIGHT # prepare initial memory ram := list(1, 0) # prepare code field codespace := [] fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 } if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) } dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write("!, SKIP, Move forward one step in current direction") write("?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++. write(" \\==-<<<<+>+++/ /=.>.+>. write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ # write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# # write() } end
872Execute SNUSP
8haskell
omi8p
>>> def factors(n): return [i for i in range(1, n + 1) if not n%i]
861Factors of an integer
3python
qz6xi
say "$_ = " . eval($_) for qw/5**3**2 (5**3)**2 5**(3**2)/;
870Exponentiation order
2perl
51ru2
import Data.CReal phi = (1 + sqrt 5) / 2 fib :: (Integral b) => b -> CReal 0 fib n = (phi^^n - (-phi)^^(-n))/sqrt 5
862Fibonacci sequence
8haskell
i9cor
int ipow(int base, int exp) { int pow = base; int v = 1; if (exp < 0) { assert (base != 0); return (base*base != 1)? 0: (exp&1)? base : 1; } while(exp > 0 ) { if (exp & 1) v *= pow; pow *= pow; exp >>= 1; } return v; } double dpow(double base, int exp) { double v=1.0; double pow = (exp <0)? 1.0/base : base; if (exp < 0) exp = - exp; while(exp > 0 ) { if (exp & 1) v *= pow; pow *= pow; exp >>= 1; } return v; } int main() { printf(, ipow(2,6)); printf(, ipow(2,-6)); printf(, dpow(2.71,6)); printf(, dpow(2.71,-6)); }
874Exponentiation operator
5c
dcinv
>>> >>> inf = 1e234 * 1e234 >>> _inf = 1e234 * -1e234 >>> _zero = 1 / _inf >>> nan = inf + _inf >>> inf, _inf, _zero, nan (inf, -inf, -0.0, nan) >>> >>> for value in (inf, _inf, _zero, nan): print (value) inf -inf -0.0 nan >>> >>> float('nan') nan >>> float('inf') inf >>> float('-inf') -inf >>> -0. -0.0 >>> >>> nan == nan False >>> nan is nan True >>> 0. == -0. True >>> 0. is -0. False >>> inf + _inf nan >>> 0.0 * nan nan >>> nan * 0.0 nan >>> 0.0 * inf nan >>> inf * 0.0 nan
865Extreme floating point values
3python
8y30o
1/c(0, -0, Inf, -Inf, NaN)
865Extreme floating point values
13r
xtdw2
const echo2 = raw""" /==!/======ECHO==,==.==# | | $==>==@/==@/==<==#""" @enum Direction left up right down function snusp(datalength, progstring) stack = Vector{Tuple{Int, Int, Direction}}() data = zeros(datalength) dp = ipx = ipy = 1 direction = right # default to go to right at beginning lines = split(progstring, "\n") lmax = maximum(map(length, lines)) lines = map(x -> rpad(x, lmax), lines) for (y, li) in enumerate(lines) if (x = findfirst("\$", li))!= nothing (ipx, ipy) = (x[1], y) end end instruction = Dict([('>', ()-> dp += 1), ('<', ()-> (dp -= 1; if dp < 0 running = false end)), ('+', ()-> data[dp] += 1), ('-', ()-> data[dp] -= 1), (',', ()-> (data[dp] = read(stdin, UInt8))), ('.', ()->print(Char(data[dp]))), ('/', ()-> (d = Int(direction); d += (iseven(d)? 3: 5); direction = Direction(d% 4))), ('\\', ()-> (d = Int(direction); d += (iseven(d)? 1: -1); direction = Direction(d))), ('!', () -> ipnext()), ('?', ()-> if data[dp] == 0 ipnext() end), ('@', ()-> push!(stack, (ipx, ipy, direction))), ('#', ()-> if length(stack) > 0 (ipx, ipy, direction) = pop!(stack) end), ('\n', ()-> (running = false))]) inboundsx(plus) = (plus? (ipx < lmax): (ipx > 1))? true: exit(data[dp]) inboundsy(plus) = (plus? (ipy < length(lines)): (ipy > 1))? true: exit(data[dp]) function ipnext() if direction == right && inboundsx(true) ipx += 1 elseif direction == left && inboundsx(false) ipx -= 1 elseif direction == down && inboundsy(true) ipy += 1 elseif direction == up && inboundsy(false) ipy -= 1 end end running = true while running cmdcode = lines[ipy][ipx] if haskey(instruction, cmdcode) instruction[cmdcode]() end ipnext() end exit(data[dp]) end snusp(100, echo2)
872Execute SNUSP
9java
wfxej
const echo2 = raw""" /==!/======ECHO==,==.==# | | $==>==@/==@/==<==#""" @enum Direction left up right down function snusp(datalength, progstring) stack = Vector{Tuple{Int, Int, Direction}}() data = zeros(datalength) dp = ipx = ipy = 1 direction = right # default to go to right at beginning lines = split(progstring, "\n") lmax = maximum(map(length, lines)) lines = map(x -> rpad(x, lmax), lines) for (y, li) in enumerate(lines) if (x = findfirst("\$", li))!= nothing (ipx, ipy) = (x[1], y) end end instruction = Dict([('>', ()-> dp += 1), ('<', ()-> (dp -= 1; if dp < 0 running = false end)), ('+', ()-> data[dp] += 1), ('-', ()-> data[dp] -= 1), (',', ()-> (data[dp] = read(stdin, UInt8))), ('.', ()->print(Char(data[dp]))), ('/', ()-> (d = Int(direction); d += (iseven(d)? 3: 5); direction = Direction(d% 4))), ('\\', ()-> (d = Int(direction); d += (iseven(d)? 1: -1); direction = Direction(d))), ('!', () -> ipnext()), ('?', ()-> if data[dp] == 0 ipnext() end), ('@', ()-> push!(stack, (ipx, ipy, direction))), ('#', ()-> if length(stack) > 0 (ipx, ipy, direction) = pop!(stack) end), ('\n', ()-> (running = false))]) inboundsx(plus) = (plus? (ipx < lmax): (ipx > 1))? true: exit(data[dp]) inboundsy(plus) = (plus? (ipy < length(lines)): (ipy > 1))? true: exit(data[dp]) function ipnext() if direction == right && inboundsx(true) ipx += 1 elseif direction == left && inboundsx(false) ipx -= 1 elseif direction == down && inboundsy(true) ipy += 1 elseif direction == up && inboundsy(false) ipy -= 1 end end running = true while running cmdcode = lines[ipy][ipx] if haskey(instruction, cmdcode) instruction[cmdcode]() end ipnext() end exit(data[dp]) end snusp(100, echo2)
872Execute SNUSP
10javascript
8yo0l
>>> 5**3**2 1953125 >>> (5**3)**2 15625 >>> 5**(3**2) 1953125 >>> >>> try: from functools import reduce except: pass >>> reduce(pow, (5, 3, 2)) 15625 >>>
870Exponentiation order
3python
4a75k
print(quote(5**3)) print(quote(5^3))
870Exponentiation order
13r
2k5lg
xx <- x <- 1:100 xx[x %% 3 == 0] <- "Fizz" xx[x %% 5 == 0] <- "Buzz" xx[x %% 15 == 0] <- "FizzBuzz" xx
835FizzBuzz
13r
jsb78
package main import ( "container/heap" "fmt" ) func main() { p := newP() fmt.Print("First twenty: ") for i := 0; i < 20; i++ { fmt.Print(p(), " ") } fmt.Print("\nBetween 100 and 150: ") n := p() for n <= 100 { n = p() } for ; n < 150; n = p() { fmt.Print(n, " ") } for n <= 7700 { n = p() } c := 0 for ; n < 8000; n = p() { c++ } fmt.Println("\nNumber beween 7,700 and 8,000:", c) p = newP() for i := 1; i < 10000; i++ { p() } fmt.Println("10,000th prime:", p()) } func newP() func() int { n := 1 var pq pQueue top := &pMult{2, 4, 0} return func() int { for { n++ if n < top.pMult {
869Extensible prime generator
0go
powbg
factors <- function(n) { if(length(n) > 1) { lapply(as.list(n), factors) } else { one.to.n <- seq_len(n) one.to.n[(n %% one.to.n) == 0] } }
861Factors of an integer
13r
anf1z
(ns anthony.random.hq9plus (:require [clojure.string:as str])) (defn bottles [] (loop [bottle 99] (if (== bottle 0) () (do (println (str bottle " bottles of beer on the wall")) (println (str bottle " bottles of beer")) (println "Take one down, pass it around") (println (str bottle " bottles of beer on the wall")) (recur (dec bottle)))))) (defn execute-hq9plus [& commands] (let [accumulator (atom 0)] (loop [pointer 0] (condp = (nth commands pointer) \H (println "Hello, world!") \Q (println (str/join commands)) \9 (bottles) \+ (reset! accumulator (inc @accumulator))) (if-not (= (inc pointer) (count commands)) (recur (inc pointer))))))
873Execute HQ9+
6clojure
dldnb
long hailstone(long, long**); void free_sequence(long *);
875Executable library
5c
enpav
. clojure.jar rosetta_code frequent_hailstone_lengths.clj hailstone_sequence.clj
875Executable library
6clojure
03xsj
null
872Execute SNUSP
11kotlin
b8pkb
#!/usr/bin/env runghc import Data.List import Data.Numbers.Primes import System.IO firstNPrimes :: Integer -> [Integer] firstNPrimes n = genericTake n primes primesBetweenInclusive :: Integer -> Integer -> [Integer] primesBetweenInclusive lo hi = dropWhile (< lo) $ takeWhile (<= hi) primes nthPrime :: Integer -> Integer nthPrime n = genericIndex primes (n - 1) main = do hSetBuffering stdout NoBuffering putStr "First 20 primes: " print $ firstNPrimes 20 putStr "Primes between 100 and 150: " print $ primesBetweenInclusive 100 150 putStr "Number of primes between 7700 and 8000: " print $ genericLength $ primesBetweenInclusive 7700 8000 putStr "The 10000th prime: " print $ nthPrime 10000
869Extensible prime generator
8haskell
f26d1
null
875Executable library
0go
9r6mt
import strutils # Requires 5 bytes of data store. const Hw = r""" /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.
872Execute SNUSP
1lua
po1bw
package main import "fmt" type F func() type If2 struct {cond1, cond2 bool} func (i If2) else1(f F) If2 { if i.cond1 && !i.cond2 { f() } return i } func (i If2) else2(f F) If2 { if i.cond2 && !i.cond1 { f() } return i } func (i If2) else0(f F) If2 { if !i.cond1 && !i.cond2 { f() } return i } func if2(cond1, cond2 bool, f F) If2 { if cond1 && cond2 { f() } return If2{cond1, cond2} } func main() { a, b := 0, 1 if2 (a == 1, b == 3, func() { fmt.Println("a = 1 and b = 3") }).else1 (func() { fmt.Println("a = 1 and b <> 3") }).else2 (func() { fmt.Println("a <> 1 and b = 3") }).else0 (func() { fmt.Println("a <> 1 and b <> 3") })
868Extend your language
0go
k0ehz
ar = [, , , ] ar.each{|exp| puts }
870Exponentiation order
14ruby
rwhgs
(defn ** [x n] (reduce * (repeat n x)))
874Exponentiation operator
6clojure
65z3q
inf = 1.0 / 0.0 nan = 0.0 / 0.0 expression = [ , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ] expression.each do |exp| puts % [exp, eval(exp)] end
865Extreme floating point values
14ruby
i9yoh
with javascript_semantics integer id = 0, ipr = 1, ipc = 1 procedure step() if and_bits(id,1) == 0 then ipc += 1 - and_bits(id,2) else ipr += 1 - and_bits(id,2) end if end procedure procedure snusp(integer dlen, string s) sequence ds = repeat(0,dlen) -- data store integer dp = 1 -- data pointer -- remove leading '\n' from string if present s = trim_head(s,'\n') -- make 2 dimensional instruction store and set instruction pointers sequence cs = split(s,'\n') ipr = 1 ipc = 1 -- look for starting instruction for i=1 to length(cs) do ipc = find('$',cs[i]) if ipc then ipr = i exit end if end for id = 0 -- execute while ipr>=1 and ipr<=length(cs) and ipc>=1 and ipc<=length(cs[ipr]) do integer op = cs[ipr][ipc] switch op do case '>' : dp += 1 case '<' : dp -= 1 case '+' : ds[dp] += 1 case '-' : ds[dp] -= 1 case '.' : puts(1,ds[dp]) case ',' : ds[dp] = getc(0) case '/' : id = not_bits(id) case '\\': id = xor_bits(id,1) case '!' : step() case '?' : if ds[dp]=0 then step() end if end switch step() end while end procedure constant hw = """ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/""" snusp(5, hw)
872Execute SNUSP
2perl
64y36
if2 :: Bool -> Bool -> a -> a -> a -> a -> a if2 p1 p2 e12 e1 e2 e = if p1 then if p2 then e12 else e1 else if p2 then e2 else e main = print $ if2 True False (error "TT") "TF" (error "FT") (error "FF")
868Extend your language
8haskell
nc3ie
fn main() { println!("5**3**2 = {:7}", 5u32.pow(3).pow(2)); println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2)); println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2))); }
870Exponentiation order
15rust
7xkrc
$ include "seed7_05.s7i"; const proc: main is func begin writeln("5**3**2 = " <& 5**3**2); writeln("(5**3)**2 = " <& (5**3)**2); writeln("5**(3**2) = " <& 5**(3**2)); end func;
870Exponentiation order
16scala
k01hk
import java.util.ArrayList; import java.util.List;
875Executable library
9java
gau4m
fn main() { let inf: f64 = 1. / 0.;
865Extreme floating point values
15rust
ncmi4
precedencegroup ExponentiationPrecedence { associativity: left higherThan: MultiplicationPrecedence } infix operator **: ExponentiationPrecedence @inlinable public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T { guard lhs!= 0 else { return 1 } var x = lhs var n = rhs var y = T(1) while n > 1 { switch n & 1 { case 0: n /= 2 case 1: y *= x n = (n - 1) / 2 case _: fatalError() } x *= x } return x * y } print(5 ** 3 ** 2) print((5 ** 3) ** 2) print(5 ** (3 ** 2))
870Exponentiation order
17swift
gej49
import java.util.*; public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0; public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); } public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); } public int count() { return count_; } private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } } private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); } private static int nextOddNumber(int n) { return 1 + 2 * (n/2); } public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
869Extensible prime generator
9java
06nse
typedef struct exception { int extype; char what[128]; } exception; typedef struct exception_ctx { exception * exs; int size; int pos; } exception_ctx; exception_ctx * Create_Ex_Ctx(int length) { const int safety = 8; char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); if (! tmp) return NULL; exception_ctx * ctx = (exception_ctx*)tmp; ctx->size = length; ctx->pos = -1; ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); return ctx; } void Free_Ex_Ctx(exception_ctx * ctx) { free(ctx); } int Has_Ex(exception_ctx * ctx) { return (ctx->pos >= 0) ? 1 : 0; } int Is_Ex_Type(exception_ctx * exctx, int extype) { return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; } void Pop_Ex(exception_ctx * ctx) { if (ctx->pos >= 0) --ctx->pos; } const char * Get_What(exception_ctx * ctx) { if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; return NULL; } int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { if (++exctx->pos == exctx->size) { --exctx->pos; fprintf(stderr, ); } snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), , msg); exctx->exs[exctx->pos].extype = extype; return -1; } exception_ctx * GLOBALEX = NULL; enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR }; void baz(int n) { if (! n) { Push_Ex(GLOBALEX, U0_DRINK_ERROR , ); return; } else { Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , ); return; } } void bar(int n) { fprintf(stdout, ); baz(n); if (Has_Ex(GLOBALEX)) goto bar_cleanup; fprintf(stdout, ); bar_cleanup: fprintf(stdout, ); } void foo() { fprintf(stdout, ); bar(0); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, , Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, ); fprintf(stdout, ); bar(1); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, , Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, ); } int main(int argc, char ** argv) { exception_ctx * ctx = Create_Ex_Ctx(5); GLOBALEX = ctx; foo(); if (Has_Ex(ctx)) goto main_ex; fprintf(stdout, ); main_ex: while (Has_Ex(ctx)) { fprintf(stderr, , Get_What(ctx)); Pop_Ex(ctx); } Free_Ex_Ctx(ctx); return 0; }
876Exceptions/Catch an exception thrown in a nested call
5c
xf1wu
#!/usr/bin/env luajit bit32=bit32 or bit local lib={ hailstone=function(n) local seq={n} while n>1 do n=bit32.band(n,1)==1 and 3*n+1 or n/2 seq[#seq+1]=n end return seq end } if arg[0] and arg[0]:match("hailstone.lua") then local function printf(fmt, ...) io.write(string.format(fmt, ...)) end local seq=lib.hailstone(27) printf("27 has%d numbers in sequence:\n",#seq) for _,i in ipairs(seq) do printf("%d ", i) end printf("\n") else return lib end
875Executable library
1lua
vkc2x
object ExtremeFloatingPoint extends App { val negInf = -1.0 / 0.0
865Extreme floating point values
16scala
tvlfb
HW = r''' /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/''' def snusp(store, code): ds = bytearray(store) dp = 0 cs = code.splitlines() ipr, ipc = 0, 0 for r, row in enumerate(cs): try: ipc = row.index('$') ipr = r break except ValueError: pass rt, dn, lt, up = range(4) id = rt def step(): nonlocal ipr, ipc if id&1: ipr += 1 - (id&2) else: ipc += 1 - (id&2) while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]): op = cs[ipr][ipc] if op == '>': dp += 1 elif op == '<': dp -= 1 elif op == '+': ds[dp] += 1 elif op == '-': ds[dp] -= 1 elif op == '.': print(chr(ds[dp]), end='') elif op == ',': ds[dp] = input() elif op == '/': id = ~id elif op == '\\': id ^= 1 elif op == '!': step() elif op == '?': if not ds[dp]: step() step() if __name__ == '__main__': snusp(5, HW)
872Execute SNUSP
3python
ygm6q
function primeGenerator(num, showPrimes) { var i, arr = []; function isPrime(num) {
869Extensible prime generator
10javascript
dl3nu
public class If2 { public static void if2(boolean firstCondition, boolean secondCondition, Runnable bothTrue, Runnable firstTrue, Runnable secondTrue, Runnable noneTrue) { if (firstCondition) if (secondCondition) bothTrue.run(); else firstTrue.run(); else if (secondCondition) secondTrue.run(); else noneTrue.run(); } }
868Extend your language
9java
qzixa
(def U0 (ex-info "U0" {})) (def U1 (ex-info "U1" {})) (defn baz [x] (if (= x 0) (throw U0) (throw U1))) (defn bar [x] (baz x)) (defn foo [] (dotimes [x 2] (try (bar x) (catch clojure.lang.ExceptionInfo e (if (= e U0) (println "foo caught U0") (throw e)))))) (defn -main [& args] (foo))
876Exceptions/Catch an exception thrown in a nested call
6clojure
oyq8j