code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
my $step = 9 * 8 * 7;
my $initial = int(9876432 / $step) * $step;
for($test = $initial; $test > 0 ; $test -= $step) {
next if $test =~ /[05]/;
next if $test =~ /(.).*\1/;
for (split '', $test) {
next unless ($test / $_) % 1;
}
printf "Found $test after%d steps\n", ($initial-$test)/$step;
for (split '', $test) {
printf "%s /%s =%s\n", $test, $_, $test / $_;
}
last
} | 661Largest number divisible by its digits
| 2perl
| levc5 |
require 'prime'
def a(n)
return 1 if n == 1 || n.prime?
(n/2).downto(1).detect{|d| n.remainder(d) == 0}
end
(1..100).map{|n| a(n).to_s.rjust(3)}.each_slice(10){|slice| puts slice.join} | 660Largest proper divisor of n
| 14ruby
| n4tit |
import Foundation
func largestProperDivisor(_ n: Int) -> Int? {
guard n > 0 else {
return nil
}
if (n & 1) == 0 {
return n >> 1
}
var p = 3
while p * p <= n {
if n% p == 0 {
return n / p
}
p += 2
}
return 1
}
for n in (1..<101) {
print(String(format: "%2d", largestProperDivisor(n)!),
terminator: n% 10 == 0? "\n": " ")
} | 660Largest proper divisor of n
| 17swift
| i5fo0 |
object LeftFactorial extends App { | 652Left factorials
| 16scala
| 5saut |
package main
import (
"github.com/fogleman/gg"
"math"
)
var dc = gg.NewContext(512, 512)
func koch(x1, y1, x2, y2 float64, iter int) {
angle := math.Pi / 3 | 672Koch curve
| 0go
| a341f |
package main
import (
"fmt"
"math/rand"
"time"
)
func sOfNCreator(n int) func(byte) []byte {
s := make([]byte, 0, n)
m := n
return func(item byte) []byte {
if len(s) < n {
s = append(s, item)
} else {
m++
if rand.Intn(m) < n {
s[rand.Intn(n)] = item
}
}
return s
}
}
func main() {
rand.Seed(time.Now().UnixNano())
var freq [10]int
for r := 0; r < 1e5; r++ {
sOfN := sOfNCreator(3)
for d := byte('0'); d < '9'; d++ {
sOfN(d)
}
for _, d := range sOfN('9') {
freq[d-'0']++
}
}
fmt.Println(freq)
} | 669Knuth's algorithm S
| 0go
| g0c4n |
null | 670Knuth's power tree
| 11kotlin
| ova8z |
func kosaraju(graph: [[Int]]) -> [Int] {
let size = graph.count
var x = size
var vis = [Bool](repeating: false, count: size)
var l = [Int](repeating: 0, count: size)
var c = [Int](repeating: 0, count: size)
var t = [[Int]](repeating: [], count: size)
func visit(_ u: Int) {
guard!vis[u] else {
return
}
vis[u] = true
for v in graph[u] {
visit(v)
t[v].append(u)
}
x -= 1
l[x] = u
}
for u in 0..<graph.count {
visit(u)
}
func assign(_ u: Int, root: Int) {
guard vis[u] else {
return
}
vis[u] = false
c[u] = root
for v in t[u] {
assign(v, root: root)
}
}
for u in l {
assign(u, root: u)
}
return c
}
let graph = [
[1],
[2],
[0],
[1, 2, 4],
[3, 5],
[2, 6],
[5],
[4, 6, 7]
]
print(kosaraju(graph: graph)) | 665Kosaraju
| 17swift
| r85gg |
package kronecker;
public class ProductFractals {
public static int[][] product(final int[][] a, final int[][] b) { | 668Kronecker product based fractals
| 9java
| 4sc58 |
import itertools
def cycler(start_items):
return itertools.cycle(start_items).__next__
def _kolakoski_gen(start_items):
s, k = [], 0
c = cycler(start_items)
while True:
c_next = c()
s.append(c_next)
sk = s[k]
yield sk
if sk > 1:
s += [c_next] * (sk - 1)
k += 1
def kolakoski(start_items=(1, 2), length=20):
return list(itertools.islice(_kolakoski_gen(start_items), length))
def _run_len_encoding(truncated_series):
return [len(list(group)) for grouper, group in itertools.groupby(truncated_series)][:-1]
def is_series_eq_its_rle(series):
rle = _run_len_encoding(series)
return (series[:len(rle)] == rle) if rle else not series
if __name__ == '__main__':
for start_items, length in [((1, 2), 20), ((2, 1), 20),
((1, 3, 1, 2), 30), ((1, 3, 2, 1), 30)]:
print(f'\n
s = kolakoski(start_items, length)
print(f' {s}')
ans = 'YES' if is_series_eq_its_rle(s) else 'NO'
print(f' Does it look like a Kolakoski sequence: {ans}') | 663Kolakoski sequence
| 3python
| 7i7rm |
use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
use List::Util qw(max);
sub Lah {
my($n, $k) = @_;
return factorial($n) if $k == 1;
return 1 if $k == $n;
return 0 if $k > $n;
return 0 if $k < 1 or $n < 1;
(factorial($n) * factorial($n - 1)) / (factorial($k) * factorial($k - 1)) / factorial($n - $k)
}
my $upto = 12;
my $mx = 1 + length max map { Lah(12,$_) } 0..$upto;
say 'Unsigned Lah numbers: L(n, k):';
print 'n\k' . sprintf "%${mx}s"x(1+$upto)."\n", 0..1+$upto;
for my $row (0..$upto) {
printf '%-3d', $row;
map { printf "%${mx}d", Lah($row, $_) } 0..$row;
print "\n";
}
say "\nMaximum value from the L(100, *) row:";
say max map { Lah(100,$_) } 0..100; | 664Lah numbers
| 2perl
| hn7jl |
null | 659Last letter-first letter
| 1lua
| vxg2x |
import Data.Bifunctor (bimap)
import Text.Printf (printf)
kochSnowflake ::
Int ->
(Float, Float) ->
(Float, Float) ->
[(Float, Float)]
kochSnowflake n a b =
concat $
zipWith (kochCurve n) points (xs <> [x])
where
points@(x: xs) = [a, equilateralApex a b, b]
kochCurve ::
Int ->
(Float, Float) ->
(Float, Float) ->
[(Float, Float)]
kochCurve n ab xy = ab: go n (ab, xy)
where
go 0 (_, xy) = [xy]
go n (ab, xy) =
let (mp, mq) = midThirdOfLine ab xy
points@(_: xs) =
[ ab,
mp,
equilateralApex mp mq,
mq,
xy
]
in go (pred n) =<< zip points xs
equilateralApex ::
(Float, Float) ->
(Float, Float) ->
(Float, Float)
equilateralApex = rotatedPoint (pi / 3)
rotatedPoint ::
Float ->
(Float, Float) ->
(Float, Float) ->
(Float, Float)
rotatedPoint theta (ox, oy) (a, b) = (ox + dx, oy - dy)
where
(dx, dy) = rotatedVector theta (a - ox, oy - b)
rotatedVector :: Float -> (Float, Float) -> (Float, Float)
rotatedVector angle (x, y) =
( x * cos angle - y * sin angle,
x * sin angle + y * cos angle
)
midThirdOfLine ::
(Float, Float) ->
(Float, Float) ->
((Float, Float), (Float, Float))
midThirdOfLine (a, b) (x, y) = (p, f p)
where
(dx, dy) = ((x - a) / 3, (y - b) / 3)
f = bimap (dx +) (dy +)
p = f (a, b)
main :: IO ()
main =
putStrLn $
svgFromPoints 1024 $
kochSnowflake 4 (200, 600) (800, 600)
svgFromPoints :: Int -> [(Float, Float)] -> String
svgFromPoints w xys =
unlines
[ "<svg xmlns=\"http://www.w3.org/2000/svg\"",
unwords
[ "width=\"512\" height=\"512\" viewBox=\"5 5",
sw,
sw,
"\"> "
],
"<path d=\"M" <> points <> "\" ",
unwords [
"stroke-width=\"2\"",
"stroke=\"red\"",
"fill=\"transparent\"/>"
],
"</svg>"
]
where
sw = show w
showN = printf "%.2g"
points =
( unwords
. fmap
( ((<>) . showN . fst)
<*> ((' ':) . showN . snd)
)
)
xys | 672Koch curve
| 8haskell
| z7qt0 |
import Control.Monad.Random
import Control.Monad.State
import qualified Data.Map as M
import System.Random
s_of_n_creator :: Int -> a -> StateT (Int, [a]) (Rand StdGen) [a]
s_of_n_creator n v = do
(i, vs) <- get
let i' = i + 1
if i' <= n
then do
let vs' = v: vs
put (i', vs')
pure vs'
else do
j <- getRandomR (1, i')
if j > n
then do
put (i', vs)
pure vs
else do
k <- getRandomR (0, n - 1)
let (f, (_: b)) = splitAt k vs
vs' = v: f ++ b
put (i', vs')
pure vs'
sample :: Int -> Rand StdGen [Int]
sample n =
let s_of_n = s_of_n_creator n
in snd <$> execStateT (traverse s_of_n [0 .. 9 :: Int]) (0, [])
incEach :: (Ord a, Num b) => M.Map a b -> [a] -> M.Map a b
incEach m ks = foldl (\m' k -> M.insertWith (+) k 1 m') m ks
sampleInc :: Int -> M.Map Int Double -> Rand StdGen (M.Map Int Double)
sampleInc n m = do
s <- sample n
pure $ incEach m s
main :: IO ()
main = do
let counts = M.empty :: M.Map Int Double
n = 100000
gen <- getStdGen
counts <- evalRandIO $ foldM (\c _ -> sampleInc 3 c) M.empty [1 .. n]
print (fmap (/ n) counts) | 669Knuth's algorithm S
| 8haskell
| scpqk |
null | 668Kronecker product based fractals
| 10javascript
| hn5jh |
package main
import "fmt"
func main() {
fmt.Println(ld("kitten", "sitting"))
}
func ld(s, t string) int {
d := make([][]int, len(s)+1)
for i := range d {
d[i] = make([]int, len(t)+1)
}
for i := range d {
d[i][0] = i
}
for j := range d[0] {
d[0][j] = j
}
for j := 1; j <= len(t); j++ {
for i := 1; i <= len(s); i++ {
if s[i-1] == t[j-1] {
d[i][j] = d[i-1][j-1]
} else {
min := d[i-1][j]
if d[i][j-1] < min {
min = d[i][j-1]
}
if d[i-1][j-1] < min {
min = d[i-1][j-1]
}
d[i][j] = min + 1
}
}
}
return d[len(s)][len(t)]
} | 656Levenshtein distance
| 0go
| jne7d |
my @lvl = [1];
my %p = (1 => 0);
sub path {
my ($n) = @_;
return () if ($n == 0);
until (exists $p{$n}) {
my @q;
foreach my $x (@{$lvl[0]}) {
foreach my $y (path($x)) {
my $z = $x + $y;
last if exists($p{$z});
$p{$z} = $x;
push @q, $z;
}
}
$lvl[0] = \@q;
}
(path($p{$n}), $n);
}
sub tree_pow {
my ($x, $n) = @_;
my %r = (0 => 1, 1 => $x);
my $p = 0;
foreach my $i (path($n)) {
$r{$i} = $r{$i - $p} * $r{$p};
$p = $i;
}
$r{$n};
}
sub show_pow {
my ($x, $n) = @_;
my $fmt = "%d:%s\n" . ("%g^%s =%f", "%s^%s =%s")[$x == int($x)] . "\n";
printf($fmt, $n, "(" . join(" ", path($n)) . ")", $x, $n, tree_pow($x, $n));
}
show_pow(2, $_) for 0 .. 17;
show_pow(1.1, 81);
{
use bigint (try => 'GMP');
show_pow(3, 191);
} | 670Knuth's power tree
| 2perl
| g094e |
def create_generator(ar)
Enumerator.new do |y|
cycle = ar.cycle
s = []
loop do
t = cycle.next
s.push(t)
v = s.shift
y << v
(v-1).times{s.push(t)}
end
end
end
def rle(ar)
ar.slice_when{|a,b| a!= b}.map(&:size)
end
[[20, [1,2]],
[20, [2,1]],
[30, [1,3,1,2]],
[30, [1,3,2,1]]].each do |num,ar|
puts
p res = create_generator(ar).take(num)
puts
end | 663Kolakoski sequence
| 14ruby
| hdhjx |
'''Largest number divisible by its digits'''
from itertools import (chain, permutations)
from functools import (reduce)
from math import (gcd)
def main():
'''Tests'''
digits = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits = reduce(lcm, digits)
sevenDigits = ((delete)(digits)(x) for x in [1, 4, 7])
print(
max(
(
intFromDigits(x) for x
in concatMap(permutations)(sevenDigits)
),
key=lambda n: n if 0 == n% lcmDigits else 0
)
)
def intFromDigits(xs):
'''An integer derived from an
ordered list of digits.
'''
return reduce(lambda a, x: a * 10 + x, xs, 0)
def concatMap(f):
'''A concatenated list over which a function has been
mapped. The list monad can be derived by using a
function f which wraps its output in a list,
(using an empty list to represent computational failure).
'''
def go(xs):
return chain.from_iterable(map(f, xs))
return go
def delete(xs):
'''xs with the first instance of
x removed.
'''
def go(x):
ys = xs.copy()
ys.remove(x)
return ys
return go
def lcm(x, y):
'''The smallest positive integer divisible
without remainder by both x and y.
'''
return 0 if (0 == x or 0 == y) else abs(
y * (x
)
if __name__ == '__main__':
main() | 661Largest number divisible by its digits
| 3python
| 2wulz |
def distance(String str1, String str2) {
def dist = new int[str1.size() + 1][str2.size() + 1]
(0..str1.size()).each { dist[it][0] = it }
(0..str2.size()).each { dist[0][it] = it }
(1..str1.size()).each { i ->
(1..str2.size()).each { j ->
dist[i][j] = [dist[i - 1][j] + 1, dist[i][j - 1] + 1, dist[i - 1][j - 1] + ((str1[i - 1] == str2[j - 1]) ? 0: 1)].min()
}
}
return dist[str1.size()][str2.size()]
}
[ ['kitten', 'sitting']: 3,
['rosettacode', 'raisethysword']: 8,
['edocattesor', 'drowsyhtesiar']: 8 ].each { key, dist ->
println "Checking distance(${key[0]}, ${key[1]}) == $dist"
assert distance(key[0], key[1]) == dist
} | 656Levenshtein distance
| 7groovy
| 5skuv |
import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n!= 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func! <T: BinaryInteger>(n: T) -> T {
guard n!= 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}
for i in 0...10 {
print("!\(i) = \(!i)")
}
print()
for i in stride(from: BigInt(20), through: 110, by: 10) {
print("!\(i) = \(!i)")
}
print()
print("!1000 = \((!BigInt(1000)).description.count) digit number")
print()
for i in stride(from: BigInt(2000), through: 10_000, by: 1000) {
print("!\(i) = \((!i).description.count) digit number")
} | 652Left factorials
| 17swift
| cah9t |
(() => {
'use strict'; | 672Koch curve
| 10javascript
| trxfm |
import java.util.*;
class SOfN<T> {
private static final Random rand = new Random();
private List<T> sample;
private int i = 0;
private int n;
public SOfN(int _n) {
n = _n;
sample = new ArrayList<T>(n);
}
public List<T> process(T item) {
if (++i <= n) {
sample.add(item);
} else if (rand.nextInt(i) < n) {
sample.set(rand.nextInt(n), item);
}
return sample;
}
}
public class AlgorithmS {
public static void main(String[] args) {
int[] bin = new int[10];
for (int trial = 0; trial < 100000; trial++) {
SOfN<Integer> s_of_n = new SOfN<Integer>(3);
for (int i = 0; i < 9; i++) s_of_n.process(i);
for (int s : s_of_n.process(9)) bin[s]++;
}
System.out.println(Arrays.toString(bin));
}
} | 669Knuth's algorithm S
| 9java
| 1zrp2 |
package main
import (
"fmt"
"strings"
)
type uintMatrix [][]uint
func (m uintMatrix) String() string {
var max uint
for _, r := range m {
for _, e := range r {
if e > max {
max = e
}
}
}
w := len(fmt.Sprint(max))
b := &strings.Builder{}
for _, r := range m {
fmt.Fprintf(b, "|%*d", w, r[0])
for _, e := range r[1:] {
fmt.Fprintf(b, "%*d", w, e)
}
fmt.Fprintln(b, "|")
}
return b.String()
}
func kronecker(m1, m2 uintMatrix) uintMatrix {
p := make(uintMatrix, len(m1)*len(m2))
for r1i, r1 := range m1 {
for r2i, r2 := range m2 {
rp := make([]uint, len(r1)*len(r2))
for c1i, e1 := range r1 {
for c2i, e2 := range r2 {
rp[c1i*len(r2)+c2i] = e1 * e2
}
}
p[r1i*len(m2)+r2i] = rp
}
}
return p
}
func sample(m1, m2 uintMatrix) {
fmt.Println("m1:")
fmt.Print(m1)
fmt.Println("m2:")
fmt.Print(m2)
fmt.Println("m1 m2:")
fmt.Print(kronecker(m1, m2))
}
func main() {
sample(uintMatrix{
{1, 2},
{3, 4},
}, uintMatrix{
{0, 5},
{6, 7},
})
sample(uintMatrix{
{0, 1, 0},
{1, 1, 1},
{0, 1, 0},
}, uintMatrix{
{1, 1, 1, 1},
{1, 0, 0, 1},
{1, 1, 1, 1},
})
} | 673Kronecker product
| 0go
| ovb8q |
null | 668Kronecker product based fractals
| 11kotlin
| la3cp |
use itertools::Itertools;
fn get_kolakoski_sequence(iseq: &[usize], size: &usize) -> Vec<usize> {
assert!(*size > 0);
assert!(!iseq.is_empty());
let mut kseq: Vec<usize> = Vec::default(); | 663Kolakoski sequence
| 15rust
| kfkh5 |
def factorial(n):
if n == 0:
return 1
res = 1
while n > 0:
res *= n
n -= 1
return res
def lah(n,k):
if k == 1:
return factorial(n)
if k == n:
return 1
if k > n:
return 0
if k < 1 or n < 1:
return 0
return (factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k)
def main():
print
print ,
for i in xrange(13):
print % i,
print
for row in xrange(13):
print % row,
for i in xrange(row + 1):
l = lah(row, i)
print % l,
print
print
maxVal = max([lah(100, a) for a in xrange(100)])
print maxVal
main() | 664Lah numbers
| 3python
| kdjhf |
null | 666Largest int from concatenated ints
| 0go
| r8ugm |
largest_LynchBell_number <- function(from, to){
from = round(from)
to = round(to)
to_chosen = to
if(to > 9876432) to = 9876432
LynchBell = NULL
range <- to:from
range <- range[range%% 5!= 0]
for(n in range){
splitted <- strsplit(toString(n), "")[[1]]
if("0"%in% splitted | "5"%in% splitted) next
if (length(splitted)!= length(unique(splitted))) next
for (i in splitted) {
if(n%% as.numeric(i)!= 0) break
if(which(splitted == i) == length(splitted)) LynchBell = n
}
if(!is.null(LynchBell)) break
}
message(paste0("The largest Lynch-Bell numer between ", from, " and ", to_chosen, " is ", LynchBell))
return(LynchBell)
}
for(i in 10^(1:8)){
largest_LynchBell_number(1, i)
} | 661Largest number divisible by its digits
| 13r
| mpcy4 |
levenshtein :: Eq a => [a] -> [a] -> Int
levenshtein s1 s2 = last $ foldl transform [0 .. length s1] s2
where
transform ns@(n:ns1) c = scanl calc (n + 1) $ zip3 s1 ns ns1
where
calc z (c1, x, y) = minimum [y + 1, z + 1, x + fromEnum (c1 /= c)]
main :: IO ()
main = print (levenshtein "kitten" "sitting") | 656Levenshtein distance
| 8haskell
| ou38p |
def bsd_rand(seed):
def rand():
rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff
return rand.seed
rand.seed = seed
return rand
def msvcrt_rand(seed):
def rand():
rand.seed = (214013*rand.seed + 2531011) & 0x7fffffff
return rand.seed >> 16
rand.seed = seed
return rand | 653Linear congruential generator
| 3python
| lehcv |
null | 669Knuth's algorithm S
| 11kotlin
| jiv7r |
from __future__ import print_function
def path(n, p = {1:0}, lvl=[[1]]):
if not n: return []
while n not in p:
q = []
for x,y in ((x, x+y) for x in lvl[0] for y in path(x) if not x+y in p):
p[y] = x
q.append(y)
lvl[0] = q
return path(p[n]) + [n]
def tree_pow(x, n):
r, p = {0:1, 1:x}, 0
for i in path(n):
r[i] = r[i-p] * r[p]
p = i
return r[n]
def show_pow(x, n):
fmt = + [, ][x==int(x)] +
print(fmt% (n, repr(path(n)), x, n, tree_pow(x, n)))
for x in range(18): show_pow(2, x)
show_pow(3, 191)
show_pow(1.1, 81) | 670Knuth's power tree
| 3python
| r8cgq |
import Data.List (transpose)
kroneckerProduct :: Num a => [[a]] -> [[a]] -> [[a]]
kroneckerProduct xs ys =
fmap (`f` ys) <$> xs
>>= fmap concat . transpose
where
f = fmap . fmap . (*)
main :: IO ()
main =
mapM_
print
( kroneckerProduct
[[1, 2], [3, 4]]
[[0, 5], [6, 7]]
)
>> putStrLn []
>> mapM_
print
( kroneckerProduct
[[0, 1, 0], [1, 1, 1], [0, 1, 0]]
[[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]]
) | 673Kronecker product
| 8haskell
| 2edll |
function prod( a, b )
local rt, l = {}, 1
for m = 1, #a do
for p = 1, #b do
rt[l] = {}
for n = 1, #a[m] do
for q = 1, #b[p] do
table.insert( rt[l], a[m][n] * b[p][q] )
end
end
l = l + 1
end
end
return rt
end
function love.load()
wid, hei = love.graphics.getWidth(), love.graphics.getHeight()
canvas = love.graphics.newCanvas( wid, hei )
mA = { {0,1,0}, {1,1,1}, {0,1,0} }; mB = { {1,0,1}, {0,1,0}, {1,0,1} }
mC = { {1,1,1}, {1,0,1}, {1,1,1} }; mD = { {1,1,1}, {0,1,0}, {1,1,1} }
end
function drawFractals( m )
love.graphics.setCanvas( canvas )
love.graphics.clear()
love.graphics.setColor( 255, 255, 255 )
for j = 1, #m do
for i = 1, #m[j] do
if m[i][j] == 1 then
love.graphics.points( i * .1, j * .1 )
end
end
end
love.graphics.setCanvas()
end
function love.keypressed( key, scancode, isrepeat )
local t = {}
if key == "a" then
print( "Build Vicsek fractal I" ); t = mA
elseif key == "b" then
print( "Build Vicsek fractal II" ); t = mB
elseif key == "c" then
print( "Sierpinski carpet fractal" ); t = mC
elseif key == "d" then
print( "Build 'H' fractal" ); t = mD
else return
end
for i = 1, 3 do t = prod( t, t ) end
drawFractals( t )
end
function love.draw()
love.graphics.draw( canvas )
end | 668Kronecker product based fractals
| 1lua
| 2e6l3 |
Lah_numbers <- function(n, k, type = "unsigned") {
if (n == k)
return(1)
if (n == 0 | k == 0)
return(0)
if (k == 1)
return(factorial(n))
if (k > n)
return(NA)
if (type == "unsigned")
return((factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k))
if (type == "signed")
return(-1 ** n * (factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k))
}
Table <- matrix(0 , 13, 13, dimnames = list(0:12, 0:12))
for (n in 0:12) {
for (k in 0:12) {
Table[n + 1, k + 1] <- Lah_numbers(n, k, type = "unsigned")
}
}
Table | 664Lah numbers
| 13r
| r84gj |
def largestInt = { c -> c.sort { v2, v1 -> "$v1$v2" <=> "$v2$v1" }.join('') as BigInteger } | 666Largest int from concatenated ints
| 7groovy
| vw928 |
import Data.List (sortBy)
import Data.Ord (comparing)
main = print (map maxcat [[1,34,3,98,9,76,45,4], [54,546,548,60]] :: [Integer])
where
sorted xs = let pad x = concat $ replicate (maxLen `div` length x + 1) x
maxLen = maximum $ map length xs
in sortBy (flip $ comparing pad) xs
maxcat = read . concat . sorted . map show | 666Largest int from concatenated ints
| 8haskell
| 0lws7 |
null | 672Koch curve
| 11kotlin
| xm7ws |
int w = 0, h = 0;
unsigned char *pix;
void refresh(int x, int y)
{
int i, j, k;
printf();
for (i = k = 0; i < h; putchar('\n'), i++)
for (j = 0; j < w; j++, k++)
putchar(pix[k] ? '
}
void walk()
{
int dx = 0, dy = 1, i, k;
int x = w / 2, y = h / 2;
pix = calloc(1, w * h);
printf();
while (1) {
i = (y * w + x);
if (pix[i]) k = dx, dx = -dy, dy = k;
else k = dy, dy = -dx, dx = k;
pix[i] = !pix[i];
printf(, y + 1, x + 1, pix[i] ? '
x += dx, y += dy;
k = 0;
if (x < 0) {
memmove(pix + 1, pix, w * h - 1);
for (i = 0; i < w * h; i += w) pix[i] = 0;
x++, k = 1;
}
else if (x >= w) {
memmove(pix, pix + 1, w * h - 1);
for (i = w-1; i < w * h; i += w) pix[i] = 0;
x--, k = 1;
}
if (y >= h) {
memmove(pix, pix + w, w * (h - 1));
memset(pix + w * (h - 1), 0, w);
y--, k = 1;
}
else if (y < 0) {
memmove(pix + w, pix, w * (h - 1));
memset(pix, 0, w);
y++, k = 1;
}
if (k) refresh(x, y);
printf(, y + 1, x + 1);
fflush(stdout);
usleep(10000);
}
}
int main(int c, char **v)
{
if (c > 1) w = atoi(v[1]);
if (c > 2) h = atoi(v[2]);
if (w < 40) w = 40;
if (h < 25) h = 25;
walk();
return 0;
} | 674Langton's ant
| 5c
| 5qtuk |
package kronecker;
public class Product {
public static int[][] product(final int[][] a, final int[][] b) { | 673Kronecker product
| 9java
| 6hs3z |
use strict;
my(%f,@m);
/^(.).*(.)$/,$f{$1}{$_}=$2 for qw(
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
);
sub poke {
our @w;
my $h = $f{$_[0]};
for my $word (keys %$h) {
my $v = $h->{$word};
delete $h->{$word};
push @w, $word;
@m = @w if @w > @m;
poke($v);
pop @w;
$h->{$word} = $v;
}
}
poke($_) for keys %f;
print @m.": @m\n"; | 659Last letter-first letter
| 2perl
| sliq3 |
magic_number = 9*8*7
div = 9876432.div(magic_number) * magic_number
candidates = div.step(0, -magic_number)
res = candidates.find do |c|
digits = c.digits
(digits & [0,5]).empty? && digits == digits.uniq
end
puts | 661Largest number divisible by its digits
| 14ruby
| uq4vz |
library(gmp)
rand_BSD <- function(n = 1) {
a <- as.bigz(1103515245)
c <- as.bigz(12345)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c)%% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c)%% m
i <- i + 1
}
as.integer(x)
}
seed <- 0
rand_BSD(10)
rand_MS <- function(n = 1) {
a <- as.bigz(214013)
c <- as.bigz(2531011)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c)%% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c)%% m
i <- i + 1
}
as.integer(x / 2^16)
}
seed <- 0
rand_MS(10) | 653Linear congruential generator
| 13r
| ybg6h |
null | 673Kronecker product
| 10javascript
| lancf |
import scala.collection.mutable
def largestDecimal: Int = Iterator.from(98764321, -1).filter(chkDec).next
def chkDec(num: Int): Boolean = {
val set = mutable.HashSet[Int]()
num.toString.toVector.map(_.asDigit).forall(d => (d != 0) && (num%d == 0) && set.add(d))
} | 661Largest number divisible by its digits
| 16scala
| rojgn |
local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
function Bitmap:render()
for y = 1, self.height do
print(table.concat(self.pixels[y]))
end
end
function Bitmap:drawKochPath(path, x, y, angle, speed, color)
local rules = {
["+"] = function() angle = angle + pi/3 end,
["-"] = function() angle = angle - pi/3 end,
["F"] = function()
local nx, ny = x+speed*cos(angle), y+speed*sin(angle)
self:line(floor(x*2+0.5), floor(y+0.5), floor(nx*2+0.5), floor(ny+0.5), color)
x, y = nx, ny
end
}
path:gsub("(.)", function(c) rules[c]() end)
end
function LSystem(axiom, rules, reps)
for i = 1, reps do
axiom = axiom:gsub("(.)", function(c) return rules[c] or c end)
end
return axiom
end
function KochPath(reps) return LSystem("F | 672Koch curve
| 1lua
| q9jx0 |
use Imager;
use Math::Cartesian::Product;
sub kronecker_product {
our @a; local *a = shift;
our @b; local *b = shift;
my @c;
cartesian {
my @cc;
cartesian {
push @cc, $_[0] * $_[1];
} [@{$_[0]}], [@{$_[1]}];
push @c, [@cc];
} [@a], [@b];
@c
}
sub kronecker_fractal {
my($order, @pattern) = @_;
my @kronecker = @pattern;
@kronecker = kronecker_product(\@kronecker, \@pattern) for 0..$order-1;
@kronecker
}
@vicsek = ( [0, 1, 0], [1, 1, 1], [0, 1, 0] );
@carpet = ( [1, 1, 1], [1, 0, 1], [1, 1, 1] );
@six = ( [0,1,1,1,0], [1,0,0,0,1], [1,0,0,0,0], [1,1,1,1,0], [1,0,0,0,1], [1,0,0,0,1], [0,1,1,1,0] );
for (['vicsek', \@vicsek, 4],
['carpet', \@carpet, 4],
['six', \@six, 3]) {
($name, $shape, $order) = @$_;
@img = kronecker_fractal( $order, @$shape );
$png = Imager->new(xsize => 1+@{$img[0]}, ysize => 1+@img);
cartesian {
$png->setpixel(x => $_[0], y => $_[1], color => $img[$_[1]][$_[0]] ? [255, 255, 32] : [16, 16, 16]);
} [0..@{$img[0]}-1], [0..$
$png->write(file => "run/kronecker-$name-perl6.png");
} | 668Kronecker product based fractals
| 2perl
| q9px6 |
def fact(n) = n.zero?? 1: 1.upto(n).inject(&:*)
def lah(n, k)
case k
when 1 then fact(n)
when n then 1
when (..1),(n..) then 0
else n<1? 0: (fact(n)*fact(n-1)) / (fact(k)*fact(k-1)) / fact(n-k)
end
end
r = (0..12)
puts
puts %11d
r.each do |row|
print % row
puts %11d
end
puts ;
puts (1..100).map{|a| lah(100,a)}.max | 664Lah numbers
| 14ruby
| ptkbh |
import java.util.*;
public class IntConcat {
private static Comparator<Integer> sorter = new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2){
String o1s = o1.toString();
String o2s = o2.toString();
if(o1s.length() == o2s.length()){
return o2s.compareTo(o1s);
}
int mlen = Math.max(o1s.length(), o2s.length());
while(o1s.length() < mlen * 2) o1s += o1s;
while(o2s.length() < mlen * 2) o2s += o2s;
return o2s.compareTo(o1s);
}
};
public static String join(List<?> things){
String output = "";
for(Object obj:things){
output += obj;
}
return output;
}
public static void main(String[] args){
List<Integer> ints1 = new ArrayList<Integer>(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4));
Collections.sort(ints1, sorter);
System.out.println(join(ints1));
List<Integer> ints2 = new ArrayList<Integer>(Arrays.asList(54, 546, 548, 60));
Collections.sort(ints2, sorter);
System.out.println(join(ints2));
}
} | 666Largest int from concatenated ints
| 9java
| a3k1y |
package main
import (
"fmt"
"math/big"
)
var m, n, z big.Int
func init() {
m.SetString("2562047788015215500854906332309589561", 10)
n.SetString("6795454494268282920431565661684282819", 10)
}
func main() {
fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
} | 667Least common multiple
| 0go
| fg8d0 |
public class Levenshtein {
public static int distance(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase(); | 656Levenshtein distance
| 9java
| wmiej |
null | 673Kronecker product
| 11kotlin
| d4anz |
(function () {
'use strict'; | 666Largest int from concatenated ints
| 10javascript
| sceqz |
def gcd
gcd = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m: m%n == 0 ? n: gcd(n, m % n) }
def lcd = { m, n -> Math.abs(m * n) / gcd(m, n) }
[[m: 12, n: 18, l: 36],
[m: -6, n: 14, l: 42],
[m: 35, n: 0, l: 0]].each { t ->
println "LCD of $t.m, $t.n is $t.l"
assert lcd(t.m, t.n) == t.l
} | 667Least common multiple
| 7groovy
| 82w0b |
function levenshtein(a, b) {
var t = [], u, i, j, m = a.length, n = b.length;
if (!m) { return n; }
if (!n) { return m; }
for (j = 0; j <= n; j++) { t[j] = j; }
for (i = 1; i <= m; i++) {
for (u = [i], j = 1; j <= n; j++) {
u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1]) + 1;
} t = u;
} return u[n];
} | 656Levenshtein distance
| 10javascript
| 8vz0l |
module LCG
module Common
attr_reader :seed
def initialize(seed)
@seed = @r = seed
end
end
class Berkeley
include Common
def rand
@r = (1103515245 * @r + 12345) & 0x7fff_ffff
end
end
class Microsoft
include Common
def rand
@r = (214013 * @r + 2531011) & 0x7fff_ffff
@r >> 16
end
end
end | 653Linear congruential generator
| 14ruby
| vxb2n |
func isLeap(year int) bool {
return year%400 == 0 || year%4 == 0 && year%100 != 0
} | 657Leap year
| 0go
| uqjvt |
use SVG;
use List::Util qw(max min);
use constant pi => 2 * atan2(1, 0);
my $koch = 'F--F--F';
$koch =~ s/F/F+F--F+F/g for 1..5;
($x, $y) = (0, 0);
$theta = pi/3;
$r = 2;
for (split //, $koch) {
if (/F/) {
push @X, sprintf "%.0f", $x;
push @Y, sprintf "%.0f", $y;
$x += $r * cos($theta);
$y += $r * sin($theta);
}
elsif (/\+/) { $theta += pi/3; }
elsif (/\-/) { $theta -= pi/3; }
}
$xrng = max(@X) - min(@X);
$yrng = max(@Y) - min(@Y);
$xt = -min(@X)+10;
$yt = -min(@Y)+10;
$svg = SVG->new(width=>$xrng+20, height=>$yrng+20);
$points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline');
$svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'});
$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");
open $fh, '>', 'koch_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh; | 672Koch curve
| 2perl
| 2eflf |
use strict;
sub s_of_n_creator {
my $n = shift;
my @sample;
my $i = 0;
sub {
my $item = shift;
$i++;
if ($i <= $n) {
push @sample, $item;
} elsif (rand() < $n / $i) {
@sample[rand $n] = $item;
}
@sample
}
}
my @items = (0..9);
my @bin;
foreach my $trial (1 .. 100000) {
my $s_of_n = s_of_n_creator(3);
my @sample;
foreach my $item (@items) {
@sample = $s_of_n->($item);
}
foreach my $s (@sample) {
$bin[$s]++;
}
}
print "@bin\n"; | 669Knuth's algorithm S
| 2perl
| tr0fg |
(let [bounds (set (range 100))
xs [1 0 -1 0] ys [0 -1 0 1]]
(loop [dir 0 x 50 y 50
grid {[x y] false}]
(if (and (bounds x) (bounds y))
(let [cur (not (grid [x y]))
dir (mod (+ dir (if cur -1 1)) 4)]
(recur dir (+ x (xs dir)) (+ y (ys dir))
(merge grid {[x y] cur})))
(doseq [col (range 100)]
(println
(apply str
(map #(if (grid [% col]) \# \.)
(range 100)))))))) | 674Langton's ant
| 6clojure
| jim7m |
function prod( a, b )
print( "\nPRODUCT:" )
for m = 1, #a do
for p = 1, #b do
for n = 1, #a[m] do
for q = 1, #b[p] do
io.write( string.format( "%3d ", a[m][n] * b[p][q] ) )
end
end
print()
end
end
end | 673Kronecker product
| 1lua
| fgedp |
import os
from PIL import Image
def imgsave(path, arr):
w, h = len(arr), len(arr[0])
img = Image.new('1', (w, h))
for x in range(w):
for y in range(h):
img.putpixel((x, y), arr[x][y])
img.save(path)
def get_shape(mat):
return len(mat), len(mat[0])
def kron(matrix1, matrix2):
final_list = []
count = len(matrix2)
for elem1 in matrix1:
for i in range(count):
sub_list = []
for num1 in elem1:
for num2 in matrix2[i]:
sub_list.append(num1 * num2)
final_list.append(sub_list)
return final_list
def kronpow(mat):
matrix = mat
while True:
yield matrix
matrix = kron(mat, matrix)
def fractal(name, mat, order=6):
path = os.path.join('fractals', name)
os.makedirs(path, exist_ok=True)
fgen = kronpow(mat)
print(name)
for i in range(order):
p = os.path.join(path, f'{i}.jpg')
print('Calculating n =', i, end='\t', flush=True)
mat = next(fgen)
imgsave(p, mat)
x, y = get_shape(mat)
print('Saved as', x, 'x', y, 'image', p)
test1 = [
[0, 1, 0],
[1, 1, 1],
[0, 1, 0]
]
test2 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
test3 = [
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]
]
fractal('test1', test1)
fractal('test2', test2)
fractal('test3', test3) | 668Kronecker product based fractals
| 3python
| sc1q9 |
from collections import defaultdict
def order_words(words):
byfirst = defaultdict(set)
for word in words:
byfirst[word[0]].add( word )
return byfirst
def linkfirst(byfirst, sofar):
'''\
For all words matching last char of last word in sofar as FIRST char and not in sofar,
return longest chain as sofar + chain
'''
assert sofar
chmatch = sofar[-1][-1]
options = byfirst[chmatch] - set(sofar)
if not options:
return sofar
else:
alternatives = ( linkfirst(byfirst, list(sofar) + [word])
for word in options )
mx = max( alternatives, key=len )
return mx
def llfl(words):
byfirst = order_words(words)
return max( (linkfirst(byfirst, [word]) for word in words), key=len )
if __name__ == '__main__':
pokemon = '''audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask'''
pokemon = pokemon.strip().lower().split()
pokemon = sorted(set(pokemon))
l = llfl(pokemon)
for i in range(0, len(l), 8): print(' '.join(l[i:i+8]))
print(len(l)) | 659Last letter-first letter
| 3python
| 02nsq |
package main
import (
"fmt"
"io/ioutil"
"sort"
"unicode"
)
const file = "unixdict.txt"
func main() {
bs, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err)
return
}
m := make(map[rune]int)
for _, r := range string(bs) {
m[r]++
} | 662Letter frequency
| 0go
| sl0qa |
extern crate rand;
pub use rand::{Rng, SeedableRng};
pub struct BsdLcg {
state: u32,
}
impl Rng for BsdLcg { | 653Linear congruential generator
| 15rust
| uqpvj |
(1900..2012).findAll {new GregorianCalendar().isLeapYear(it)}.each {println it} | 657Leap year
| 7groovy
| 915m4 |
gpKronFractal <- function(m, n, pf, clr, ttl, dflg=0, psz=600) {
cat(" *** START:", date(), "n=", n, "clr=", clr, "psz=", psz, "\n");
cat(" *** Plot file -", pf, "\n");
r <- m;
for(i in 1:n) {r = r%x%m};
plotmat(r, pf, clr, ttl, dflg, psz);
cat(" *** END:", date(), "\n");
}
M <- matrix(c(0,1,0,1,1,1,0,1,0), ncol=3, nrow=3, byrow=TRUE);
gpKronFractal(M, 4, "VicsekFractalR","red", "Vicsek Fractal n=4")
M <- matrix(c(1,1,1,1,0,1,1,1,1), ncol=3, nrow=3, byrow=TRUE);
gpKronFractal(M, 4, "SierpinskiCarpetFR", "maroon", "Sierpinski carpet fractal n=4")
M <- matrix(c(1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,0,1,1,1,1,0,0,0,0,0,1,1,1,1,
+0,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1), ncol=7, nrow=7, byrow=TRUE);
gpKronFractal(M, 3, "PlusSignFR", "maroon", "Plus sign fractal, n=3") | 668Kronecker product based fractals
| 13r
| e6had |
import BigInt
import Foundation
@inlinable
public func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n!= 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
@inlinable
public func lah<T: BinaryInteger>(n: T, k: T) -> T {
if k == 1 {
return factorial(n)
} else if k == n {
return 1
} else if k > n {
return 0
} else if k < 1 || n < 1 {
return 0
} else {
let a = (factorial(n) * factorial(n - 1))
let b = (factorial(k) * factorial(k - 1))
let c = factorial(n - k)
return a / b / c
}
}
print("Unsigned Lah numbers: L(n, k):")
print("n\\k", terminator: "")
for i in 0...12 {
print(String(format: "%10d", i), terminator: " ")
}
print()
for row in 0...12 {
print(String(format: "%-2d", row), terminator: "")
for i in 0...row {
lah(n: BigInt(row), k: BigInt(i)).description.withCString {str in
print(String(format: "%11s", str), terminator: "")
}
}
print()
}
let maxLah = (0...100).map({ lah(n: BigInt(100), k: BigInt($0)) }).max()!
print("Maximum value from the L(100, *) row: \(maxLah)") | 664Lah numbers
| 17swift
| bfhkd |
import kotlin.Comparator
fun main(args: Array<String>) {
val comparator = Comparator<Int> { x, y -> "$x$y".compareTo("$y$x") }
fun findLargestSequence(array: IntArray): String {
return array.sortedWith(comparator.reversed()).joinToString("") { it.toString() }
}
for (array in listOf(
intArrayOf(1, 34, 3, 98, 9, 76, 45, 4),
intArrayOf(54, 546, 548, 60),
)) {
println("%s ->%s".format(array.contentToString(), findLargestSequence(array)))
}
} | 666Largest int from concatenated ints
| 11kotlin
| hngj3 |
lcm :: (Integral a) => a -> a -> a
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((x `quot` (gcd x y)) * y) | 667Least common multiple
| 8haskell
| 4sl5s |
def frequency = { it.inject([:]) { map, value -> map[value] = (map[value] ?: 0) + 1; map } }
frequency(new File('frequency.groovy').text).each { key, value ->
println "'$key': $value"
} | 662Letter frequency
| 7groovy
| a6e1p |
object LinearCongruentialGenerator {
def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
override def hasNext:Boolean=true
override def next:Int={seed=(seed * 1103515245 + 12345) & Int.MaxValue; seed}
}
def msRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{
var seed=rseed
override def hasNext:Boolean=true
override def next:Int={seed=(seed * 214013 + 2531011) & Int.MaxValue; seed >> 16}
}
def toString(it:Iterator[Int], n:Int=20)=it take n mkString ", "
def main(args:Array[String]){
println("-- seed 0 --")
println("BSD: "+ toString(bsdRandom(0)))
println("MS: "+ toString(msRandom(0)))
println("-- seed 1 --")
println("BSD: "+ toString(bsdRandom(1)))
println("MS: "+ toString( msRandom(1)))
}
} | 653Linear congruential generator
| 16scala
| g8e4i |
<?php
function s_of_n_creator($n) {
$sample = array();
$i = 0;
return function($item) use (&$sample, &$i, $n) {
$i++;
if ($i <= $n) {
$sample[] = $item;
} else if (rand(0, $i-1) < $n) {
$sample[rand(0, $n-1)] = $item;
}
return $sample;
};
}
$items = range(0, 9);
for ($trial = 0; $trial < 100000; $trial++) {
$s_of_n = s_of_n_creator(3);
foreach ($items as $item)
$sample = $s_of_n($item);
foreach ($sample as $s)
$bin[$s]++;
}
print_r($bin);
?> | 669Knuth's algorithm S
| 12php
| kd5hv |
function icsort(numbers)
table.sort(numbers,function(x,y) return (x..y) > (y..x) end)
return numbers
end
for _,numbers in pairs({{1, 34, 3, 98, 9, 76, 45, 4}, {54, 546, 548, 60}}) do
print(('Numbers: {%s}\n Largest integer:%s'):format(
table.concat(numbers,","),table.concat(icsort(numbers))
))
end | 666Largest int from concatenated ints
| 1lua
| kdrh2 |
import java.util.Scanner;
public class LCM{
public static void main(String[] args){
Scanner aScanner = new Scanner(System.in); | 667Least common multiple
| 9java
| c139h |
import Data.List
import Control.Monad
import Control.Arrow
leaptext x b | b = show x ++ " is a leap year"
| otherwise = show x ++ " is not a leap year"
isleapsf j | 0==j`mod`100 = 0 == j`mod`400
| otherwise = 0 == j`mod`4 | 657Leap year
| 8haskell
| wmoed |
from random import randrange
def s_of_n_creator(n):
sample, i = [], 0
def s_of_n(item):
nonlocal i
i += 1
if i <= n:
sample.append(item)
elif randrange(i) < n:
sample[randrange(n)] = item
return sample
return s_of_n
if __name__ == '__main__':
bin = [0]* 10
items = range(10)
print()
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
print(% (item, sample))
for trial in range(100000):
s_of_n = s_of_n_creator(3)
for item in items:
sample = s_of_n(item)
for s in sample:
bin[s] += 1
print(,
'\n '.join(% x for x in enumerate(bin))) | 669Knuth's algorithm S
| 3python
| z78tt |
function LCM(A) | 667Least common multiple
| 10javascript
| 5qcur |
null | 656Levenshtein distance
| 11kotlin
| btqkb |
import Data.List (group,sort)
import Control.Arrow ((&&&))
main = interact (show . map (head &&& length) . group . sort) | 662Letter frequency
| 8haskell
| 91cmo |
'''Koch curve'''
from math import cos, pi, sin
from operator import add, sub
from itertools import chain
def kochSnowflake(n, a, b):
'''List of points on a Koch snowflake of order n, derived
from an equilateral triangle with base a b.
'''
points = [a, equilateralApex(a, b), b]
return chain.from_iterable(map(
kochCurve(n),
points,
points[1:] + [points[0]]
))
def kochCurve(n):
'''List of points on a Koch curve of order n,
starting at point ab, and ending at point xy.
'''
def koch(n):
def goTuple(abxy):
ab, xy = abxy
if 0 == n:
return [xy]
else:
mp, mq = midThirdOfLine(ab, xy)
points = [
ab,
mp,
equilateralApex(mp, mq),
mq,
xy
]
return list(
chain.from_iterable(map(
koch(n - 1),
zip(points, points[1:])
))
)
return goTuple
def go(ab, xy):
return [ab] + koch(n)((ab, xy))
return go
def equilateralApex(p, q):
'''Apex of triangle with base p q.
'''
return rotatedPoint(pi / 3)(p, q)
def rotatedPoint(theta):
'''The point ab rotated theta radians
around the origin xy.
'''
def go(xy, ab):
ox, oy = xy
a, b = ab
dx, dy = rotatedVector(theta, (a - ox, oy - b))
return ox + dx, oy - dy
return go
def rotatedVector(theta, xy):
'''The vector xy rotated by theta radians.
'''
x, y = xy
return (
x * cos(theta) - y * sin(theta),
x * sin(theta) + y * cos(theta)
)
def midThirdOfLine(ab, xy):
'''Second of three equal segments of
the line between ab and xy.
'''
vector = [x / 3 for x in map(sub, xy, ab)]
def f(p):
return tuple(map(add, vector, p))
p = f(ab)
return (p, f(p))
def main():
'''SVG for Koch snowflake of order 4.
'''
print(
svgFromPoints(1024)(
kochSnowflake(
4, (200, 600), (800, 600)
)
)
)
def svgFromPoints(w):
'''Width of square canvas -> Point list -> SVG string.
'''
def go(xys):
xs = ' '.join(map(
lambda xy: str(round(xy[0], 2)) + ' ' + str(round(xy[1], 2)),
xys
))
return '\n'.join([
'<svg xmlns=',
f'width= height= viewBox=>',
f'<path d= ',
'stroke-width= stroke= fill=/>',
'</svg>'
])
return go
if __name__ == '__main__':
main() | 672Koch curve
| 3python
| vwt29 |
use strict;
use warnings;
use PDL;
sub kron {
my ($x, $y) = @_;
return $x->dummy(0)
->dummy(0)
->mult($y, 0)
->clump(0, 2)
->clump(1, 2)
}
my @mats = (
[pdl([[1, 2], [3, 4]]),
pdl([[0, 5], [6, 7]])],
[pdl([[0, 1, 0], [1, 1, 1], [0, 1, 0]]),
pdl([[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]])],
);
for my $mat (@mats) {
print "A = $mat->[0]\n";
print "B = $mat->[1]\n";
print "kron(A,B) = " . kron($mat->[0], $mat->[1]) . "\n";
} | 673Kronecker product
| 2perl
| ji97f |
use std::{
fmt::{Debug, Display, Write},
ops::Mul,
}; | 668Kronecker product based fractals
| 15rust
| ovw83 |
class LastL_FirstL
def initialize(names)
@names = names.dup
@first = names.group_by {|name| name[0]}
@sequences = []
end
def add_name(seq)
last_letter = seq[-1][-1]
potentials = @first.include?(last_letter)? (@first[last_letter] - seq): []
if potentials.empty?
@sequences << seq
else
potentials.each {|name| add_name(seq + [name])}
end
end
def search
@names.each {|name| add_name [name]}
max = @sequences.max_by {|seq| seq.length}.length
max_seqs = @sequences.select {|seq| seq.length == max}
puts
puts
puts
max_seqs.last.each_with_index {|name, idx| puts % [idx+1, name]}
end
end
names = %w{
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
}
lf = LastL_FirstL.new(names)
lf.search | 659Last letter-first letter
| 14ruby
| ouf8v |
package main
import (
"fmt"
"os"
"strconv"
"time"
)
func main() {
y := time.Now().Year()
if len(os.Args) == 2 {
if i, err := strconv.Atoi(os.Args[1]); err == nil {
y = i
}
}
for m := time.January; m <= time.December; m++ {
d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour)
d = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour)
fmt.Println(d.Format("2006-01-02"))
}
} | 671Last Friday of each month
| 0go
| e6ra6 |
null | 659Last letter-first letter
| 15rust
| i5tod |
import java.util.GregorianCalendar;
import java.text.MessageFormat;
public class Leapyear{
public static void main(String[] argv){
int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
GregorianCalendar cal = new GregorianCalendar();
for(int year : yrs){
System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
year, cal.isLeapYear(year), isLeapYear(year)));
}
}
public static boolean isLeapYear(int year){
return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
}
} | 657Leap year
| 9java
| kfwhm |
def s_of_n_creator(n)
sample = []
i = 0
Proc.new do |item|
i += 1
if i <= n
sample << item
elsif rand(i) < n
sample[rand(n)] = item
end
sample
end
end
frequency = Array.new(10,0)
100_000.times do
s_of_n = s_of_n_creator(3)
sample = nil
(0..9).each {|digit| sample = s_of_n[digit]}
sample.each {|digit| frequency[digit] += 1}
end
(0..9).each {|digit| puts } | 669Knuth's algorithm S
| 14ruby
| 6hi3t |
use rand::{Rng,weak_rng};
struct SofN<R: Rng+Sized, T> {
rng: R,
sample: Vec<T>,
i: usize,
n: usize,
}
impl<R: Rng, T> SofN<R, T> {
fn new(rng: R, n: usize) -> Self {
SofN{rng, sample: Vec::new(), i: 0, n}
}
fn add(&mut self, item: T) {
self.i += 1;
if self.i <= self.n {
self.sample.push(item);
} else if self.rng.gen_range(0, self.i) < self.n {
self.sample[self.rng.gen_range(0, self.n)] = item;
}
}
fn sample(&self) -> &Vec<T> {
&self.sample
}
}
pub fn main() {
const MAX: usize = 10;
let mut bin: [i32; MAX] = Default::default();
for _ in 0..100000 {
let mut s_of_n = SofN::new(weak_rng(), 3);
for i in 0..MAX { s_of_n.add(i); }
for s in s_of_n.sample() {
bin[*s] += 1;
}
}
for (i, x) in bin.iter().enumerate() {
println!("frequency of {}: {}", i, x);
}
} | 669Knuth's algorithm S
| 15rust
| ykn68 |
def ymd = { it.format('yyyy-MM-dd') }
def lastFridays = lastWeekDays.curry(Day.Fri)
lastFridays(args[0] as int).each { println (ymd(it)) } | 671Last Friday of each month
| 7groovy
| kdvh7 |
object LastLetterFirstLetterNaive extends App {
def solve(names: Set[String]) = {
def extend(solutions: List[List[String]]): List[List[String]] = {
val more = solutions.flatMap{solution =>
val lastLetter = solution.head takeRight 1
(names -- solution).filter(_.take(1) equalsIgnoreCase lastLetter).map(_ :: solution)
}
if (more.isEmpty) solutions else extend(more)
}
extend(names.toList.map(List(_))).map(_.reverse)
}
val names70 = Set("audino", "bagon", "baltoy", "banette", "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", "croagunk", "darmanitan", "deino", "emboar", "emolga", "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", "relicanth", "remoraid", "rufflet", "sableye", "scolipede", "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", "whismur", "wingull", "yamask")
val solutions = solve(names70)
println(s"Maximum path length: ${solutions.head.length}")
println(s"Paths of that length: ${solutions.size}")
println("Example path of that length:")
println(solutions.head.sliding(7,7).map(_.mkString(" ")).map(" "+_).mkString("\n"))
} | 659Last letter-first letter
| 16scala
| fr6d4 |
fun main(args: Array<String>) {
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
println(lcm(15, 9))
} | 667Least common multiple
| 11kotlin
| 3jnz5 |
import Cocoa
class LinearCongruntialGenerator {
var state = 0 | 653Linear congruential generator
| 17swift
| 2wklj |
var isLeapYear = function (year) { return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); }; | 657Leap year
| 10javascript
| ey8ao |
import java.util
import scala.util.Random
object KnuthsAlgorithmS extends App {
import scala.collection.JavaConverters._
val (n, rand, bin) = (3, Random, new Array[Int](10))
for (_ <- 0 until 100000) {
val sample = new util.ArrayList[Int](n)
for (item <- 0 until 10) {
if (item < n) sample.add(item)
else if (rand.nextInt(item + 1) < n)
sample.asScala(rand.nextInt(n)) = item
}
for (s <- sample.asScala.toList) bin(s) += 1
}
println(bin.mkString("[", ", ", "]"))
} | 669Knuth's algorithm S
| 16scala
| c1t93 |
import Data.Time.Calendar
(Day, addDays, showGregorian, fromGregorian, gregorianMonthLength)
import Data.Time.Calendar.WeekDate (toWeekDate)
import Data.List (transpose, intercalate)
findWeekDay :: Int -> Day -> Day
findWeekDay dayOfWeek date =
head
(filter
(\x ->
let (_, _, day) = toWeekDate x
in day == dayOfWeek)
((`addDays` date) <$> [-6 .. 0]))
weekDayDates :: Int -> Integer -> [String]
weekDayDates dayOfWeek year =
((showGregorian . findWeekDay dayOfWeek) .
(fromGregorian year <*> gregorianMonthLength year)) <$>
[1 .. 12]
main :: IO ()
main =
mapM_
putStrLn
(intercalate " " <$> transpose (weekDayDates 5 <$> [2012 .. 2017])) | 671Last Friday of each month
| 8haskell
| 3j0zj |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class LetterFreq {
public static int[] countLetters(String filename) throws IOException{
int[] freqs = new int[26];
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while((line = in.readLine()) != null){
line = line.toUpperCase();
for(char ch:line.toCharArray()){
if(Character.isLetter(ch)){
freqs[ch - 'A']++;
}
}
}
in.close();
return freqs;
}
public static void main(String[] args) throws IOException{
System.out.println(Arrays.toString(countLetters("filename.txt")));
}
} | 662Letter frequency
| 9java
| t7zf9 |
attr_reader :koch
def settings
size 600, 600
end
def setup
sketch_title '2D Koch'
@koch = KochSnowflake.new
koch.create_grammar 5
no_loop
end
def draw
background 0
koch.render
end
class Grammar
attr_reader :axiom, :rules
def initialize(axiom, rules)
@axiom = axiom
@rules = rules
end
def apply_rules(prod)
prod.gsub(/./) { |token| rules.fetch(token, token) }
end
def generate(gen)
return axiom if gen.zero?
prod = axiom
gen.times do
prod = apply_rules(prod)
end
prod
end
end
Turtle = Struct.new(:x, :y, :theta)
class KochSnowflake
include Processing::Proxy
attr_reader :grammar, :axiom, :draw_length, :production, :turtle
DELTA = 60.radians
def initialize
@axiom = 'F--F--F'
@grammar = Grammar.new(
axiom,
'F' => 'F+F--F+F'
)
@draw_length = 20
stroke 0, 255, 0
stroke_weight 2
@turtle = Turtle.new(width / 5, height * 0.7, 0)
end
def render
production.scan(/./) do |element|
case element
when 'F'
draw_line(turtle)
when '+'
turtle.theta += DELTA
when '-'
turtle.theta -= DELTA
when 'L', 'R'
else puts 'Grammar not recognized'
end
end
end
def draw_line(turtle)
x_temp = turtle.x
y_temp = turtle.y
@turtle.x += draw_length * Math.cos(turtle.theta)
@turtle.y += draw_length * Math.sin(turtle.theta)
line(x_temp, y_temp, turtle.x, turtle.y)
end
def create_grammar(gen)
@draw_length *= 0.6**gen
@production = @grammar.generate gen
end
end | 672Koch curve
| 14ruby
| 5q3uj |
import Darwin
func s_of_n_creator<T>(n: Int) -> T -> [T] {
var sample = [T]()
var i = 0
return {(item: T) in
i++
if (i <= n) {
sample.append(item)
} else if (Int(arc4random_uniform(UInt32(i))) < n) {
sample[Int(arc4random_uniform(UInt32(n)))] = item
}
return sample
}
}
var bin = [Int](count:10, repeatedValue:0)
for trial in 0..<100000 {
let s_of_n: Int -> [Int] = s_of_n_creator(3)
var sample: [Int] = []
for i in 0..<10 {
sample = s_of_n(i)
}
for s in sample {
bin[s]++
}
}
println(bin) | 669Knuth's algorithm S
| 17swift
| 3joz2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.