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) { ... | 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) {
... | 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 {
... | 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 {
r... | 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)... | 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($... | 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) ... | 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'
e... | 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... | 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;
... | 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,... | 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 ... | 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 -... | 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... | 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) {
... | 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.Builde... | 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) * factor... | 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% splitte... | 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" "sitti... | 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 ... | 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]]
)
... | 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
en... | 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)) / fac... | 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 $ com... | 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... | 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 lumine... | 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 <- functi... | 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,
["-"] = functi... | 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 kro... | 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..10... | 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()){
... | 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])... | 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 ... | 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... | 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
... | 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]... | 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)... | 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 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,... | 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 {
... | 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(
i... | 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
... | 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;
}
... | 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
... | 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.fr... | 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]]),
... | 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
... | 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.A... | 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){
... | 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[... | 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 <= se... | 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 lastLe... | 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(it... | 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) = toWe... | 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;... | 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
d... | 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... | 669Knuth's algorithm S | 17swift | 3joz2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.