code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
is_leap_year ()
{
declare -i year=$1
echo -n "$year ($2)-> "
if (( $year % 4 == 0 ))
then
if (( $year % 400 == 0 ))
then
echo "This is a leap year"
else
if (( $year % 100 == 0 ))
then
echo "This is not a leap year"
else
echo "This is a leap year"
fi
fi
else
echo "This is not a leap year"
fi
}
is_leap_year 1900 not
is_leap_year 2000 is
is_leap_year 2001 not
is_leap_year 2003 not
is_leap_year 2004 is | 657Leap year
| 4bash
| qcnxu |
package main
import (
"fmt"
"sort"
)
type matrix [][]int | 658Latin Squares in reduced form
| 0go
| 7ipr2 |
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import Data.Monoid ((<>))
triangles
:: (Map.Map Int Int -> Int -> Int -> Int -> Int -> Maybe Int)
-> Int
-> [(Int, Int, Int)]
triangles f n =
let mapRoots = Map.fromList $ ((,) =<< (^ 2)) <$> [1 .. n]
in Set.elems $
foldr
(\(suma2b2, a, b) triSet ->
(case f mapRoots suma2b2 (a * b) a b of
Just c -> Set.insert (a, b, c) triSet
_ -> triSet))
(Set.fromList [])
([1 .. n] >>=
(\a -> (flip (,,) a =<< (a * a +) . (>>= id) (*)) <$> [1 .. a]))
f90, f60, f60ne, f120 :: Map.Map Int Int -> Int -> Int -> Int -> Int -> Maybe Int
f90 dct x2 ab a b = Map.lookup x2 dct
f60 dct x2 ab a b = Map.lookup (x2 - ab) dct
f120 dct x2 ab a b = Map.lookup (x2 + ab) dct
f60ne dct x2 ab a b
| a == b = Nothing
| otherwise = Map.lookup (x2 - ab) dct
main :: IO ()
main = do
putStrLn
(unlines $
"Triangles of maximum side 13\n":
zipWith
(\f n ->
let solns = triangles f 13
in show (length solns) <> " solutions for " <> show n <>
" degrees:\n" <>
unlines (show <$> solns))
[f120, f90, f60]
[120, 90, 60])
putStrLn "60 degrees - uneven triangles of maximum side 10000. Total:"
print $ length $ triangles f60ne 10000 | 655Law of cosines - triples
| 8haskell
| 5sbug |
def leo( n:Int, n1:Int=1, n2:Int=1, addnum:Int=1 ) : BigInt = n match {
case 0 => n1
case 1 => n2
case n => leo(n - 1, n1, n2, addnum) + leo(n - 2, n1, n2, addnum) + addnum
}
{
println( "The first 25 Leonardo Numbers:")
(0 until 25) foreach { n => print( leo(n) + " " ) }
println( "\n\nThe first 25 Fibonacci Numbers:")
(0 until 25) foreach { n => print( leo(n, n1=0, n2=1, addnum=0) + " " ) }
} | 651Leonardo numbers
| 16scala
| kfohk |
import Data.List (permutations, (\\))
import Control.Monad (foldM, forM_)
latinSquares :: Eq a => [a] -> [[[a]]]
latinSquares [] = []
latinSquares set = map reverse <$> squares
where
squares = foldM addRow firstRow perm
perm = tail (groupedPermutations set)
firstRow = pure <$> set
addRow tbl rows = [ zipWith (:) row tbl
| row <- rows
, and $ different (tail row) (tail tbl) ]
different = zipWith $ (not .) . elem
groupedPermutations :: Eq a => [a] -> [[[a]]]
groupedPermutations lst = map (\x -> (x:) <$> permutations (lst \\ [x])) lst
printTable :: Show a => [[a]] -> IO ()
printTable tbl = putStrLn $ unlines $ unwords . map show <$> tbl | 658Latin Squares in reduced form
| 8haskell
| 8vf0z |
public class LawOfCosines {
public static void main(String[] args) {
generateTriples(13);
generateTriples60(10000);
}
private static void generateTriples(int max) {
for ( int coeff : new int[] {0, -1, 1} ) {
int count = 0;
System.out.printf("Max side length%d, formula: a*a + b*b%s= c*c%n", max, coeff == 0 ? "" : (coeff<0 ? "-" : "+") + " a*b ");
for ( int a = 1 ; a <= max ; a++ ) {
for ( int b = 1 ; b <= a ; b++ ) {
int val = a*a + b*b + coeff*a*b;
int c = (int) (Math.sqrt(val) + .5d);
if ( c > max ) {
break;
}
if ( c*c == val ) {
System.out.printf(" (%d,%d,%d)%n", a, b ,c);
count++;
}
}
}
System.out.printf("%d triangles%n", count);
}
}
private static void generateTriples60(int max) {
int count = 0;
System.out.printf("%nExtra Credit.%nMax side length%d, sides different length, formula: a*a + b*b - a*b = c*c%n", max);
for ( int a = 1 ; a <= max ; a++ ) {
for ( int b = 1 ; b < a ; b++ ) {
int val = a*a + b*b - a*b;
int c = (int) (Math.sqrt(val) + .5d);
if ( c*c == val ) {
count++;
}
}
}
System.out.printf("%d triangles%n", count);
}
} | 655Law of cosines - triples
| 9java
| 91gmu |
null | 652Left factorials
| 11kotlin
| 13npd |
package main
import "fmt" | 653Linear congruential generator
| 0go
| pzobg |
struct Leonardo: Sequence, IteratorProtocol {
private let add: Int
private var n0: Int
private var n1: Int
init(n0: Int = 1, n1: Int = 1, add: Int = 1) {
self.n0 = n0
self.n1 = n1
self.add = add
}
mutating func next() -> Int? {
let n = n0
n0 = n1
n1 += n + add
return n
}
}
print("First 25 Leonardo numbers:")
print(Leonardo().prefix(25).map{String($0)}.joined(separator: " "))
print("First 25 Fibonacci numbers:")
print(Leonardo(n0: 0, add: 0).prefix(25).map{String($0)}.joined(separator: " ")) | 651Leonardo numbers
| 17swift
| g8x49 |
typedef struct {
uint16_t index;
char last_char, first_char;
} Ref;
Ref* longest_path_refs;
size_t longest_path_refs_len;
Ref* refs;
size_t refs_len;
size_t n_solutions;
const char** longest_path;
size_t longest_path_len;
void search(size_t curr_len) {
if (curr_len == longest_path_refs_len) {
n_solutions++;
} else if (curr_len > longest_path_refs_len) {
n_solutions = 1;
longest_path_refs_len = curr_len;
memcpy(longest_path_refs, refs, curr_len * sizeof(Ref));
}
intptr_t last_char = refs[curr_len - 1].last_char;
for (size_t i = curr_len; i < refs_len; i++)
if (refs[i].first_char == last_char) {
Ref aux = refs[curr_len];
refs[curr_len] = refs[i];
refs[i] = aux;
search(curr_len + 1);
refs[i] = refs[curr_len];
refs[curr_len] = aux;
}
}
void find_longest_chain(const char* items[],
size_t items_len) {
refs_len = items_len;
refs = calloc(refs_len, sizeof(Ref));
longest_path_refs_len = 0;
longest_path_refs = calloc(refs_len, sizeof(Ref));
for (size_t i = 0; i < items_len; i++) {
size_t itemsi_len = strlen(items[i]);
if (itemsi_len <= 1)
exit(1);
refs[i].index = (uint16_t)i;
refs[i].last_char = items[i][itemsi_len - 1];
refs[i].first_char = items[i][0];
}
for (size_t i = 0; i < items_len; i++) {
Ref aux = refs[0];
refs[0] = refs[i];
refs[i] = aux;
search(1);
refs[i] = refs[0];
refs[0] = aux;
}
longest_path_len = longest_path_refs_len;
longest_path = calloc(longest_path_len, sizeof(const char*));
for (size_t i = 0; i < longest_path_len; i++)
longest_path[i] = items[longest_path_refs[i].index];
free(longest_path_refs);
free(refs);
}
int main() {
const char* pokemon[] = {, , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , ,
, , , , , ,
, , , , ,
, , , , };
size_t pokemon_len = sizeof(pokemon) / sizeof(pokemon[0]);
find_longest_chain(pokemon, pokemon_len);
printf(, longest_path_len);
printf(, n_solutions);
printf();
for (size_t i = 0; i < longest_path_len; i += 7) {
printf();
for (size_t j = i; j < (i+7) && j < longest_path_len; j++)
printf(, longest_path[j]);
printf();
}
free(longest_path);
return 0;
} | 659Last letter-first letter
| 5c
| eysav |
unsigned int lpd(unsigned int n) {
if (n<=1) return 1;
int i;
for (i=n-1; i>0; i--)
if (n%i == 0) return i;
}
int main() {
int i;
for (i=1; i<=100; i++) {
printf(, lpd(i));
if (i % 10 == 0) printf();
}
return 0;
} | 660Largest proper divisor of n
| 5c
| x90wu |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LatinSquaresInReducedForm {
public static void main(String[] args) {
System.out.printf("Reduced latin squares of order 4:%n");
for ( LatinSquare square : getReducedLatinSquares(4) ) {
System.out.printf("%s%n", square);
}
System.out.printf("Compute the number of latin squares from count of reduced latin squares:%n(Reduced Latin Square Count) * n! * (n-1)! = Latin Square Count%n");
for ( int n = 1 ; n <= 6 ; n++ ) {
List<LatinSquare> list = getReducedLatinSquares(n);
System.out.printf("Size =%d,%d *%d *%d =%,d%n", n, list.size(), fact(n), fact(n-1), list.size()*fact(n)*fact(n-1));
}
}
private static long fact(int n) {
if ( n == 0 ) {
return 1;
}
int prod = 1;
for ( int i = 1 ; i <= n ; i++ ) {
prod *= i;
}
return prod;
}
private static List<LatinSquare> getReducedLatinSquares(int n) {
List<LatinSquare> squares = new ArrayList<>();
squares.add(new LatinSquare(n));
PermutationGenerator permGen = new PermutationGenerator(n);
for ( int fillRow = 1 ; fillRow < n ; fillRow++ ) {
List<LatinSquare> squaresNext = new ArrayList<>();
for ( LatinSquare square : squares ) {
while ( permGen.hasMore() ) {
int[] perm = permGen.getNext(); | 658Latin Squares in reduced form
| 9java
| ey0a5 |
(() => {
'use strict'; | 655Law of cosines - triples
| 10javascript
| uqkvb |
bsd = tail . iterate (\n -> (n * 1103515245 + 12345) `mod` 2^31)
msr = map (`div` 2^16) . tail . iterate (\n -> (214013 * n + 2531011) `mod` 2^31)
main = do
print $ take 10 $ bsd 0
print $ take 10 $ msr 0 | 653Linear congruential generator
| 8haskell
| fr2d1 |
int main()
{
int num = 9876432,diff[] = {4,2,2,2},i,j,k=0;
char str[10];
start:snprintf(str,10,,num);
for(i=0;str[i+1]!=00;i++){
if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){
num -= diff[k];
k = (k+1)%4;
goto start;
}
for(j=i+1;str[j]!=00;j++)
if(str[i]==str[j]){
num -= diff[k];
k = (k+1)%4;
goto start;
}
}
printf(,num);
return 0;
} | 661Largest number divisible by its digits
| 5c
| yb96f |
int frequency[26];
int ch;
FILE* txt_file = fopen (, );
for (ch = 0; ch < 26; ch++)
frequency[ch] = 0;
while (1) {
ch = fgetc(txt_file);
if (ch == EOF) break;
if ('a' <= ch && ch <= 'z')
frequency[ch-'a']++;
else if ('A' <= ch && ch <= 'Z')
frequency[ch-'A']++;
} | 662Letter frequency
| 5c
| vxu2o |
null | 652Left factorials
| 1lua
| a6d1v |
typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1 | 658Latin Squares in reduced form
| 11kotlin
| kfeh3 |
null | 655Law of cosines - triples
| 11kotlin
| zj2ts |
[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2] | 650List comprehensions
| 3python
| 5swux |
int is_leap_year(int year)
{
return (!(year % 4) && year % 100 || !(year % 400)) ? 1 : 0;
}
int main()
{
int test_case[] = {1900, 1994, 1996, 1997, 2000}, key, end, year;
for (key = 0, end = sizeof(test_case)/sizeof(test_case[0]); key < end; ++key) {
year = test_case[key];
printf(, year, (is_leap_year(year) == 1 ? : ));
}
} | 657Leap year
| 5c
| 02fst |
(ns rosetta-code.last-letter-first-letter
(:require clojure.string))
(defn by-first-letter
"Returns a map from letters to a set of words that start with that letter"
[words]
(into {} (map (fn [[k v]]
[k (set v)]))
(group-by first words)))
(defn longest-path-from
"Find a longest path starting at word, using only words-by-first-letter for successive words.
Returns a pair of [length list-of-words] to describe the path."
[word words-by-first-letter]
(let [words-without-word (update words-by-first-letter (first word)
disj word)
next-words (words-without-word (last word))]
(if (empty? next-words)
[1 [word]]
(let [sub-paths (map #(longest-path-from % words-without-word) next-words)
[length words-of-path] (apply max-key first sub-paths)]
[(inc length) (cons word words-of-path)]))))
(defn longest-word-chain
"Find a longest path among the words in word-list, by performing a longest path search
starting at each word in the list."
[word-list]
(let [words-by-letter (by-first-letter word-list)]
(apply max-key first
(pmap #(longest-path-from % words-by-letter)
word-list))))
(defn word-list-from-file [file-name]
(let [contents (slurp file-name)
words (clojure.string/split contents #"[ \n]")]
(filter #(not (empty? %)) words)))
(time (longest-word-chain (word-list-from-file "pokemon.txt"))) | 659Last letter-first letter
| 6clojure
| 02nsj |
function solve(angle, maxlen, filter)
local squares, roots, solutions = {}, {}, {}
local cos2 = ({[60]=-1,[90]=0,[120]=1})[angle]
for i = 1, maxlen do squares[i], roots[i^2] = i^2, i end
for a = 1, maxlen do
for b = a, maxlen do
local lhs = squares[a] + squares[b] + cos2*a*b
local c = roots[lhs]
if c and (not filter or filter(a,b,c)) then
solutions[#solutions+1] = {a=a,b=b,c=c}
end
end
end
print(angle.." on 1.."..maxlen.." has "..#solutions.." solutions")
if not filter then
for i,v in ipairs(solutions) do print("",v.a,v.b,v.c) end
end
end
solve(90, 13)
solve(60, 13)
solve(120, 13)
function fexcr(a,b,c) return a~=b or b~=c end
solve(60, 10000, fexcr) | 655Law of cosines - triples
| 1lua
| 3hvzo |
x = (0:10)
> x^2
[1] 0 1 4 9 16 25 36 49 64 81 100
> Reduce(function(y,z){return (y+z)},x)
[1] 55
> x[x[(0:length(x))]%% 2==0]
[1] 0 2 4 6 8 10 | 650List comprehensions
| 13r
| lepce |
import java.util.stream.IntStream;
import static java.util.stream.IntStream.iterate;
public class LinearCongruentialGenerator {
final static int mask = (1 << 31) - 1;
public static void main(String[] args) {
System.out.println("BSD:");
randBSD(0).limit(10).forEach(System.out::println);
System.out.println("\nMS:");
randMS(0).limit(10).forEach(System.out::println);
}
static IntStream randBSD(int seed) {
return iterate(seed, s -> (s * 1_103_515_245 + 12_345) & mask).skip(1);
}
static IntStream randMS(int seed) {
return iterate(seed, s -> (s * 214_013 + 2_531_011) & mask).skip(1)
.map(i -> i >> 16);
}
} | 653Linear congruential generator
| 9java
| 026se |
(require '[clojure.string:as str])
(def the_base 16)
(def digits (rest (range the_base)))
(def primes [])
(for [n digits] (if (= 1 (count (filter (fn[m] (and (< m n) (= 0 (mod n m)))) digits)) ) (def primes (conj primes n))))
(defn duplicity [n p partial] (if (= 0 (mod n p)) (duplicity (/ n p) p (conj partial p)) partial))
(defn factorize [n] (let [a (flatten (for [p (filter #(< % n) primes)]
(remove #(= 1 %) (duplicity n p [1]))))] (if (= 0 (count a)) (lazy-seq [n]) a) ))
(defn multiplicity [s n] (count (filter #(= n %) s)))
(defn combine [x y] (concat x (flatten (for [w (dedupe y)] (repeat (- (multiplicity y w) (multiplicity x w)) w) ))))
(defn lcm [s] (reduce * (reduce combine (map factorize s))))
(defn exp [x n] (reduce * (repeat n x)))
(defn non_empty_subsets [s] (for [x (reverse (rest (range (exp 2 (count s)))))]
(remove nil? (for [i (range (count s))] (if (bit-test x i) (nth s i))))))
(defn power_up [s] (reduce + (loop [idx (- (count s) 1) s_next s]
(if (zero? idx) s_next (recur (dec idx) (map-indexed #(if (< %1 idx) (* %2 the_base) %2) s_next))))))
(defn max_for_digits [s] (power_up (sort #(> %1 %2) s)))
(defn min_for_digits [s] (power_up (sort #(< %1 %2) s)))
(defn log_base [x] (/ (Math/log x) (Math/log the_base)))
(defn remove_zeros [s] (remove #(= % 0) s))
(defn first_multiple_not_after [n ub] (loop [m ub] (if (= 0 (mod m n)) m (recur (dec m)))))
(defn representation [n] (let [full_power (int (log_base n))]
(loop [power full_power place (exp the_base full_power) rep [] rem n ] (if (= power -1) rep
(recur (dec power) (/ place the_base) (conj rep (int (/ rem place))) (- rem (* place (int (/ rem place)))))))))
(defn digit_qualifies [m s] (let [rep_m (representation m)] (= (sort s) (sort rep_m))))
(defn find_s_largest_lb [s] (let [lb (min_for_digits s)] (let [m (lcm s)]
(loop [v (first_multiple_not_after m (max_for_digits s))] (if (< v lb) []
(if (digit_qualifies v s) (representation v) (recur (- v m))))))))
(defn find_largest_lb [] (let [subsets (non_empty_subsets (reverse digits))]
(loop [s_size (- the_base 1)] (let [hits (remove #(= (count %) 0) (map find_s_largest_lb (filter #(= (count %) s_size) subsets)))]
(if (pos? (count hits)) (first (sort #(first (remove_zeros (map - %2 %1))) hits)) (recur (dec s_size)))))))
(defn hex_digit [v] (case v 15 "F" 14 "E" 13 "D" 12 "C" 11 "B" 10 "A" (str v)))
(find_largest_lb) | 661Largest number divisible by its digits
| 6clojure
| 2wul1 |
use strict;
use warnings;
my $n = 0;
my $count;
our @perms;
while( ++$n <= 7 )
{
$count = 0;
@perms = perm( my $start = join '', 1 .. $n );
find( $start );
print "order $n size $count total @{[$count * fact($n) * fact($n-1)]}\n\n";
}
sub find
{
@_ >= $n and return $count += ($n != 4) || print join "\n", @_, "\n";
local @perms = grep 0 == ($_[-1] ^ $_) =~ tr/\0//, @perms;
my $row = @_ + 1;
find( @_, $_ ) for grep /^$row/, @perms;
}
sub fact { $_[0] > 1 ? $_[0] * fact($_[0] - 1) : 1 }
sub perm
{
my $s = shift;
length $s <= 1 ? $s :
map { my $f = $_; map "$f$_", perm( $s =~ s/$_//r ) } split //, $s;
} | 658Latin Squares in reduced form
| 2perl
| 3hczs |
(println (sort-by second >
(frequencies (map #(java.lang.Character/toUpperCase %)
(filter #(java.lang.Character/isLetter %) (slurp "text.txt")))))) | 662Letter frequency
| 6clojure
| ro7g2 |
use utf8;
binmode STDOUT, "utf8:";
use Sort::Naturally;
sub triples {
my($n,$angle) = @_;
my(@triples,%sq);
$sq{$_**2}=$_ for 1..$n;
for $a (1..$n-1) {
for $b ($a+1..$n) {
my $ab = $a*$a + $b*$b;
my $cos = $angle == 60 ? $ab - $a * $b :
$angle == 120 ? $ab + $a * $b :
$ab;
if ($angle == 60) {
push @triples, "$a $sq{$cos} $b" if exists $sq{$cos};
} else {
push @triples, "$a $b $sq{$cos}" if exists $sq{$cos};
}
}
}
@triples;
}
$n = 13;
print "Integer triangular triples for sides 1..$n:\n";
for my $angle (120, 90, 60) {
my @itt = triples($n,$angle);
if ($angle == 60) { push @itt, "$_ $_ $_" for 1..$n }
printf "Angle%3d has%2d solutions:%s\n", $angle, scalar @itt,
join ', ', nsort @itt;
}
printf "Non-equilateral n=10000/60:%d\n", scalar triples(10000,60); | 655Law of cosines - triples
| 2perl
| btsk4 |
use 5.010;
use strict;
use warnings;
use bigint;
sub leftfact {
my ($n) = @_;
state $cached = 0;
state $factorial = 1;
state $leftfact = 0;
if( $n < $cached ) {
($cached, $factorial, $leftfact) = (0, 1, 0);
}
while( $n > $cached ) {
$leftfact += $factorial;
$factorial *= ++$cached;
}
return $leftfact;
}
printf "!%d =%s\n", $_, leftfact($_) for 0 .. 10, map $_*10, 2..11;
printf "!%d has%d digits.\n", $_, length leftfact($_) for map $_*1000, 1..10; | 652Left factorials
| 2perl
| mp7yz |
(defn leap-year? [y]
(and (zero? (mod y 4)) (or (pos? (mod y 100)) (zero? (mod y 400))))) | 657Leap year
| 6clojure
| dgynb |
typedef int bool;
int next_in_cycle(int *c, int len, int index) {
return c[index % len];
}
void kolakoski(int *c, int *s, int clen, int slen) {
int i = 0, j, k = 0;
while (TRUE) {
s[i] = next_in_cycle(c, clen, k);
if (s[k] > 1) {
for (j = 1; j < s[k]; ++j) {
if (++i == slen) return;
s[i] = s[i - 1];
}
}
if (++i == slen) return;
k++;
}
}
bool possible_kolakoski(int *s, int len) {
int i, j = 0, prev = s[0], count = 1;
int *rle = calloc(len, sizeof(int));
bool result = TRUE;
for (i = 1; i < len; ++i) {
if (s[i] == prev) {
count++;
}
else {
rle[j++] = count;
count = 1;
prev = s[i];
}
}
for (i = 0; i < j; i++) {
if (rle[i] != s[i]) {
result = FALSE;
break;
}
}
free(rle);
return result;
}
void print_array(int *a, int len) {
int i;
printf();
for (i = 0; i < len; ++i) {
printf(, a[i]);
if (i < len - 1) printf();
}
printf();
}
int main() {
int i, clen, slen, *s;
int c0[2] = {1, 2};
int c1[2] = {2, 1};
int c2[4] = {1, 3, 1, 2};
int c3[4] = {1, 3, 2, 1};
int *cs[4] = {c0, c1, c2, c3};
bool p;
int clens[4] = {2, 2, 4, 4};
int slens[4] = {20, 20, 30, 30};
for (i = 0; i < 4; ++i) {
clen = clens[i];
slen = slens[i];
s = calloc(slen, sizeof(int));
kolakoski(cs[i], s, clen, slen);
printf(, slen);
print_array(cs[i], clen);
printf();
print_array(s, slen);
printf();
p = possible_kolakoski(s, slen);
printf(, p ? : );
free(s);
}
return 0;
} | 663Kolakoski sequence
| 5c
| uquv4 |
uint64_t factorial(uint64_t n) {
uint64_t res = 1;
if (n == 0) return res;
while (n > 0) res *= n--;
return res;
}
uint64_t lah(uint64_t n, uint64_t k) {
if (k == 1) return factorial(n);
if (k == n) return 1;
if (k > n) return 0;
if (k < 1 || n < 1) return 0;
return (factorial(n) * factorial(n - 1)) / (factorial(k) * factorial(k - 1)) / factorial(n - k);
}
int main() {
int row, i;
printf();
printf();
for (i = 0; i < 13; i++) {
printf(, i);
}
printf();
for (row = 0; row < 13; row++) {
printf(, row);
for (i = 0; i < row + 1; i++) {
uint64_t l = lah(row, i);
printf(, l);
}
printf();
}
return 0;
} | 664Lah numbers
| 5c
| g0545 |
package main
import "fmt"
func largestProperDivisor(n int) int {
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return n / i
}
}
return 1
}
func main() {
fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
fmt.Print(" 1 ")
for n := 2; n <= 100; n++ {
if n%2 == 0 {
fmt.Printf("%2d ", n/2)
} else {
fmt.Printf("%2d ", largestProperDivisor(n))
}
if n%10 == 0 {
fmt.Println()
}
}
} | 660Largest proper divisor of n
| 0go
| leucw |
def dList(n, start):
start -= 1
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
r = []
def recurse(last):
if (last == first):
for j,v in enumerate(a[1:]):
if j + 1 == v:
return
b = [x + 1 for x in a]
r.append(b)
return
for i in xrange(last, 0, -1):
a[i], a[last] = a[last], a[i]
recurse(last - 1)
a[i], a[last] = a[last], a[i]
recurse(n - 1)
return r
def printSquare(latin,n):
for row in latin:
print row
print
def reducedLatinSquares(n,echo):
if n <= 0:
if echo:
print []
return 0
elif n == 1:
if echo:
print [1]
return 1
rlatin = [None] * n
for i in xrange(n):
rlatin[i] = [None] * n
for j in xrange(0, n):
rlatin[0][j] = j + 1
class OuterScope:
count = 0
def recurse(i):
rows = dList(n, i)
for r in xrange(len(rows)):
rlatin[i - 1] = rows[r]
justContinue = False
k = 0
while not justContinue and k < i - 1:
for j in xrange(1, n):
if rlatin[k][j] == rlatin[i - 1][j]:
if r < len(rows) - 1:
justContinue = True
break
if i > 2:
return
k += 1
if not justContinue:
if i < n:
recurse(i + 1)
else:
OuterScope.count += 1
if echo:
printSquare(rlatin, n)
recurse(2)
return OuterScope.count
def factorial(n):
if n == 0:
return 1
prod = 1
for i in xrange(2, n + 1):
prod *= i
return prod
print
reducedLatinSquares(4,True)
print
print
for n in xrange(1, 7):
size = reducedLatinSquares(n, False)
f = factorial(n - 1)
f *= f * n * size
print % (n, size, n, n - 1, f) | 658Latin Squares in reduced form
| 3python
| 6kl3w |
null | 653Linear congruential generator
| 11kotlin
| eyda4 |
import Data.List.Split (chunksOf)
import Text.Printf (printf)
lpd :: Int -> Int
lpd 1 = 1
lpd n = head [x | x <- [n -1, n -2 .. 1], n `mod` x == 0]
main :: IO ()
main =
(putStr . unlines . map concat . chunksOf 10) $
printf "%3d" . lpd <$> [1 .. 100] | 660Largest proper divisor of n
| 8haskell
| 13wps |
n = 20
r = ((1..n).flat_map { |x|
(x..n).flat_map { |y|
(y..n).flat_map { |z|
[[x, y, z]].keep_if { x * x + y * y == z * z }}}})
p r | 650List comprehensions
| 14ruby
| g8q4q |
package main
import "fmt"
var g = [][]int{
0: {1},
1: {2},
2: {0},
3: {1, 2, 4},
4: {3, 5},
5: {2, 6},
6: {5},
7: {4, 6, 7},
}
func main() {
fmt.Println(kosaraju(g))
}
func kosaraju(g [][]int) []int { | 665Kosaraju
| 0go
| q9exz |
int catcmp(const void *a, const void *b)
{
char ab[32], ba[32];
sprintf(ab, , *(int*)a, *(int*)b);
sprintf(ba, , *(int*)b, *(int*)a);
return strcmp(ba, ab);
}
void maxcat(int *a, int len)
{
int i;
qsort(a, len, sizeof(int), catcmp);
for (i = 0; i < len; i++)
printf(, a[i]);
putchar('\n');
}
int main(void)
{
int x[] = {1, 34, 3, 98, 9, 76, 45, 4};
int y[] = {54, 546, 548, 60};
maxcat(x, sizeof(x)/sizeof(x[0]));
maxcat(y, sizeof(y)/sizeof(y[0]));
return 0;
} | 666Largest int from concatenated ints
| 5c
| n50i6 |
int gcd(int m, int n)
{
int tmp;
while(m) { tmp = m; m = n % m; n = tmp; }
return n;
}
int lcm(int m, int n)
{
return m / gcd(m, n) * n;
}
int main()
{
printf(, lcm(21,35));
return 0;
} | 667Least common multiple
| 5c
| ji570 |
def printSquare(a)
for row in a
print row,
end
print
end
def dList(n, start)
start = start - 1
a = Array.new(n) {|i| i}
a[0], a[start] = a[start], a[0]
a[1..] = a[1..].sort
first = a[1]
r = []
recurse = lambda {|last|
if last == first then
a[1..].each_with_index {|v, j|
if j + 1 == v then
return
end
}
b = a.map { |i| i + 1 }
r << b
return
end
i = last
while i >= 1 do
a[i], a[last] = a[last], a[i]
recurse.call(last - 1)
a[i], a[last] = a[last], a[i]
i = i - 1
end
}
recurse.call(n - 1)
return r
end
def reducedLatinSquares(n, echo)
if n <= 0 then
if echo then
print
end
return 0
end
if n == 1 then
if echo then
print
end
return 1
end
rlatin = Array.new(n) { Array.new(n, Float::NAN)}
for j in 0 .. n - 1
rlatin[0][j] = j + 1
end
count = 0
recurse = lambda {|i|
rows = dList(n, i)
for r in 0 .. rows.length - 1
rlatin[i - 1] = rows[r].dup
catch (:outer) do
for k in 0 .. i - 2
for j in 1 .. n - 1
if rlatin[k][j] == rlatin[i - 1][j] then
if r < rows.length - 1 then
throw :outer
end
if i > 2 then
return
end
end
end
end
if i < n then
recurse.call(i + 1)
else
count = count + 1
if echo then
printSquare(rlatin)
end
end
end
end
}
recurse.call(2)
return count
end
def factorial(n)
if n == 0 then
return 1
end
prod = 1
for i in 2 .. n
prod = prod * i
end
return prod
end
print
reducedLatinSquares(4, true)
print
print
for n in 1 .. 6
size = reducedLatinSquares(n, false)
f = factorial(n - 1)
f = f * f * n * size
print % [n, size, n, n - 1, f]
end | 658Latin Squares in reduced form
| 14ruby
| mpvyj |
N = 13
def method1(N=N):
squares = [x**2 for x in range(0, N+1)]
sqrset = set(squares)
tri90, tri60, tri120 = (set() for _ in range(3))
for a in range(1, N+1):
a2 = squares[a]
for b in range(1, a + 1):
b2 = squares[b]
c2 = a2 + b2
if c2 in sqrset:
tri90.add(tuple(sorted((a, b, int(c2**0.5)))))
ab = a * b
c2 -= ab
if c2 in sqrset:
tri60.add(tuple(sorted((a, b, int(c2**0.5)))))
c2 += 2 * ab
if c2 in sqrset:
tri120.add(tuple(sorted((a, b, int(c2**0.5)))))
return sorted(tri90), sorted(tri60), sorted(tri120)
if __name__ == '__main__':
print(f'Integer triangular triples for sides 1..{N}:')
for angle, triples in zip([90, 60, 120], method1(N)):
print(f' {angle:3} has {len(triples)} solutions:\n {triples}')
_, t60, _ = method1(10_000)
notsame = sum(1 for a, b, c in t60 if a != b or b != c)
print('Extra credit:', notsame) | 655Law of cosines - triples
| 3python
| pz0bm |
fn pyth(n: u32) -> impl Iterator<Item = [u32; 3]> {
(1..=n).flat_map(move |x| {
(x..=n).flat_map(move |y| {
(y..=n).filter_map(move |z| {
if x.pow(2) + y.pow(2) == z.pow(2) {
Some([x, y, z])
} else {
None
}
})
})
})
} | 650List comprehensions
| 15rust
| rosg5 |
local RNG = {
new = function(class, a, c, m, rand)
local self = setmetatable({}, class)
local state = 0
self.rnd = function()
state = (a * state + c) % m
return rand and rand(state) or state
end
self.seed = function(new_seed)
state = new_seed % m
end
return self
end
}
bsd = RNG:new(1103515245, 12345, 1<<31)
ms = RNG:new(214013, 2531011, 1<<31, function(s) return s>>16 end)
print"BSD:"
for _ = 1,10 do
print(("\t%10d"):format(bsd.rnd()))
end
print"Microsoft:"
for _ = 1,10 do
print(("\t%10d"):format(ms.rnd()))
end | 653Linear congruential generator
| 1lua
| wmfea |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
public class Kosaraju {
static class Recursive<I> {
I func;
}
private static List<Integer> kosaraju(List<List<Integer>> g) { | 665Kosaraju
| 9java
| fgidv |
typedef struct{
int row, col;
}cell;
int ROW,COL,SUM=0;
unsigned long raiseTo(int base,int power){
if(power==0)
return 1;
else
return base*raiseTo(base,power-1);
}
cell* kroneckerProduct(char* inputFile,int power){
FILE* fp = fopen(inputFile,);
int i,j,k,l;
unsigned long prod;
int** matrix;
cell *coreList,*tempList,*resultList;
fscanf(fp,,&ROW,&COL);
matrix = (int**)malloc(ROW*sizeof(int*));
for(i=0;i<ROW;i++){
matrix[i] = (int*)malloc(COL*sizeof(int));
for(j=0;j<COL;j++){
fscanf(fp,,&matrix[i][j]);
if(matrix[i][j]==1)
SUM++;
}
}
coreList = (cell*)malloc(SUM*sizeof(cell));
resultList = (cell*)malloc(SUM*sizeof(cell));
k = 0;
for(i=0;i<ROW;i++){
for(j=0;j<COL;j++){
if(matrix[i][j]==1){
coreList[k].row = i+1;
coreList[k].col = j+1;
resultList[k].row = i+1;
resultList[k].col = j+1;
k++;
}
}
}
prod = k;
for(i=2;i<=power;i++){
tempList = (cell*)malloc(prod*k*sizeof(cell));
l = 0;
for(j=0;j<prod;j++){
for(k=0;k<SUM;k++){
tempList[l].row = (resultList[j].row-1)*ROW + coreList[k].row;
tempList[l].col = (resultList[j].col-1)*COL + coreList[k].col;
l++;
}
}
free(resultList);
prod *= k;
resultList = (cell*)malloc(prod*sizeof(cell));
for(j=0;j<prod;j++){
resultList[j].row = tempList[j].row;
resultList[j].col = tempList[j].col;
}
free(tempList);
}
return resultList;
}
int main(){
char fileName[100];
int power,i,length;
cell* resultList;
printf();
scanf(,fileName);
printf();
scanf(,&power);
resultList = kroneckerProduct(fileName,power);
initwindow(raiseTo(ROW,power),raiseTo(COL,power),);
length = raiseTo(SUM,power);
for(i=0;i<length;i++){
putpixel(resultList[i].row,resultList[i].col,15);
}
getch();
closegraph();
return 0;
} | 668Kronecker product based fractals
| 5c
| a3j11 |
package main
import (
"fmt"
"strings"
)
var pokemon = `audino bagon baltoy...67 names omitted...`
func main() { | 659Last letter-first letter
| 0go
| 91vmt |
package main
import (
"fmt"
"strconv"
"strings"
)
func divByAll(num int, digits []byte) bool {
for _, digit := range digits {
if num%int(digit-'0') != 0 {
return false
}
}
return true
}
func main() {
magic := 9 * 8 * 7
high := 9876432 / magic * magic
for i := high; i >= magic; i -= magic {
if i%10 == 0 {
continue | 661Largest number divisible by its digits
| 0go
| 13ep5 |
(defn gcd
[a b]
(if (zero? b)
a
(recur b, (mod a b))))
(defn lcm
[a b]
(/ (* a b) (gcd a b)))
(defn lcmv [& v] (reduce lcm v)) | 667Least common multiple
| 6clojure
| 1zjpy |
inputs <- cbind(combn(1:13, 2), rbind(seq_len(13), seq_len(13)))
inputs <- cbind(A = inputs[1, ], B = inputs[2, ])[sort.list(inputs[1, ]),]
Pythagoras <- inputs[, "A"]^2 + inputs[, "B"]^2
AtimesB <- inputs[, "A"] * inputs[, "B"]
CValues <- sqrt(cbind("C (90)" = Pythagoras,
"C (60)" = Pythagoras - AtimesB,
"C (120)" = Pythagoras + AtimesB))
CValues[!t(apply(CValues, MARGIN = 1, function(x) x %in% 1:13))] <- NA
output <- cbind(inputs, CValues)[!apply(CValues, MARGIN = 1, function(x) all(is.na(x))),]
rownames(output) <- paste0("Solution ", seq_len(nrow(output)), ":")
print(output, na.print = "")
cat("There are",
sum(!is.na(output[, 3])), "solutions in the 90 case,",
sum(!is.na(output[, 4])), "solutions in the 60 case, and",
sum(!is.na(output[, 5])), "solutions in the 120 case.") | 655Law of cosines - triples
| 13r
| jnw78 |
def pythagoranTriangles(n: Int) = for {
x <- 1 to 21
y <- x to 21
z <- y to 21
if x * x + y * y == z * z
} yield (x, y, z) | 650List comprehensions
| 16scala
| hdoja |
class Leap {
bool leapYear(num year) {
return (year% 400 == 0) || (( year% 100!= 0) && (year% 4 == 0));
bool isLeapYear(int year) =>
(year% 4 == 0) && ((year% 100!= 0) || (year% 400 == 0)); | 657Leap year
| 18dart
| a601h |
null | 665Kosaraju
| 11kotlin
| 82q0q |
package main
import "fmt"
func nextInCycle(c []int, index int) int {
return c[index % len(c)]
}
func kolakoski(c []int, slen int) []int {
s := make([]int, slen)
i, k := 0, 0
for {
s[i] = nextInCycle(c, k)
if s[k] > 1 {
for j := 1; j < s[k]; j++ {
i++
if i == slen {
return s
}
s[i] = s[i - 1]
}
}
i++
if i == slen {
return s
}
k++
}
}
func possibleKolakoski(s []int) bool {
slen := len(s)
rle := make([]int, 0, slen)
prev := s[0]
count := 1
for i := 1; i < slen; i++ {
if s[i] == prev {
count++
} else {
rle = append(rle, count)
count = 1
prev = s[i]
}
} | 663Kolakoski sequence
| 0go
| 020sk |
import Data.List
import qualified Data.ByteString.Char8 as B
allPokemon :: [B.ByteString]
allPokemon = map B.pack $ words
"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"
growChains :: [[B.ByteString]] -> [B.ByteString]
growChains pcs
| nextChainSet == [] = head pcs
| otherwise = growChains nextChainSet
where nextChainSet = pcs >>= findLinks
findLinks pc = map (\x -> pc ++ [x]) $ filter (isLink $ last pc) (allPokemon \\ pc)
isLink pl pr = B.last pl == B.head pr
main = mapM_ B.putStrLn $ growChains $ map (\x -> [x]) allPokemon | 659Last letter-first letter
| 8haskell
| btek2 |
import Data.List (maximumBy, permutations, delete)
import Data.Ord (comparing)
import Data.Bool (bool)
unDigits :: [Int] -> Int
unDigits = foldl ((+) . (10 *)) 0
ds :: [Int]
ds = [1, 2, 3, 4, 6, 7, 8, 9]
lcmDigits :: Int
lcmDigits = foldr1 lcm ds
sevenDigits :: [[Int]]
sevenDigits = (`delete` ds) <$> [1, 4, 7]
main :: IO ()
main =
print $
maximumBy
(comparing (bool 0 <*> (0 ==) . (`rem` lcmDigits)))
(unDigits <$> concat (permutations <$> sevenDigits)) | 661Largest number divisible by its digits
| 8haskell
| t73f7 |
use strict;
use warnings;
use ntheory 'divisors';
use List::AllUtils <max natatime>;
sub proper_divisors {
my $n = shift;
return 1 if $n == 0;
my @d = divisors($n);
pop @d;
@d;
}
my @range = 1 .. 100;
print "GPD for $range[0] through $range[-1]:\n";
my $iter = natatime 10, @range;
while( my @batch = $iter->() ) {
printf '%3d', $_ == 1 ? 1 : max proper_divisors($_) for @batch; print "\n";
} | 660Largest proper divisor of n
| 2perl
| 8vn0w |
from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r'% [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10):
print(lf)
print('Digits in 1,000 through 10,000 (inclusive) by thousands:\n %r'
% [len(str(lf)) for lf in islice(lfact(), 1000, 10001, 1000)] ) | 652Left factorials
| 3python
| 91jmf |
struct s_env {
unsigned int n, i;
size_t size;
void *sample;
};
void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n)
{
s_env->i = 0;
s_env->n = n;
s_env->size = size;
s_env->sample = malloc(n * size);
}
void sample_set_i(struct s_env *s_env, unsigned int i, void *item)
{
memcpy(s_env->sample + i * s_env->size, item, s_env->size);
}
void *s_of_n(struct s_env *s_env, void *item)
{
s_env->i++;
if (s_env->i <= s_env->n)
sample_set_i(s_env, s_env->i - 1, item);
else if ((rand() % s_env->i) < s_env->n)
sample_set_i(s_env, rand() % s_env->n, item);
return s_env->sample;
}
int *test(unsigned int n, int *items_set, unsigned int num_items)
{
int i;
struct s_env s_env;
s_of_n_init(&s_env, sizeof(items_set[0]), n);
for (i = 0; i < num_items; i++) {
s_of_n(&s_env, (void *) &items_set[i]);
}
return (int *)s_env.sample;
}
int main()
{
unsigned int i, j;
unsigned int n = 3;
unsigned int num_items = 10;
unsigned int *frequencies;
int *items_set;
srand(time(NULL));
items_set = malloc(num_items * sizeof(int));
frequencies = malloc(num_items * sizeof(int));
for (i = 0; i < num_items; i++) {
items_set[i] = i;
frequencies[i] = 0;
}
for (i = 0; i < 100000; i++) {
int *res = test(n, items_set, num_items);
for (j = 0; j < n; j++) {
frequencies[res[j]]++;
}
free(res);
}
for (i = 0; i < num_items; i++) {
printf(, frequencies[i]);
}
puts();
return 0;
} | 669Knuth's algorithm S
| 5c
| iuwo2 |
function write_array(a)
io.write("[")
for i=0,#a do
if i>0 then
io.write(", ")
end
io.write(tostring(a[i]))
end
io.write("]")
end
function kosaraju(g) | 665Kosaraju
| 1lua
| ovs8h |
import Data.List (group)
import Control.Monad (forM_)
replicateAtLeastOne :: Int -> a -> [a]
replicateAtLeastOne n x = x: replicate (n-1) x
zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWithLazy f ~(x:xs) ~(y:ys) = f x y: zipWithLazy f xs ys
kolakoski :: [Int] -> [Int]
kolakoski items = s
where s = concat $ zipWithLazy replicateAtLeastOne s $ cycle items
rle :: Eq a => [a] -> [Int]
rle = map length . group
sameAsRleUpTo :: Int -> [Int] -> Bool
sameAsRleUpTo n s = r == take (length r) prefix
where prefix = take n s
r = init $ rle prefix
main :: IO ()
main = forM_ [([1, 2], 20),
([2, 1], 20),
([1, 3, 1, 2], 30),
([1, 3, 2, 1], 30)]
$ \(items, n) -> do
putStrLn $ "First " ++ show n ++ " members of the sequence generated by " ++ show items ++ ":"
let s = kolakoski items
print $ take n s
putStrLn $ "Possible Kolakoski sequence? " ++ show (sameAsRleUpTo n s)
putStrLn "" | 663Kolakoski sequence
| 8haskell
| cac94 |
library(gmp)
left_factorial <- function(n) {
if (n == 0) return(0)
result <- as.bigz(0)
adder <- as.bigz(1)
for (k in 1:n) {
result <- result + adder
adder <- adder * k
}
result
}
digit_count <- function(n) {
nchar(as.character(n))
}
for (n in 0:10) {
cat("!",n," = ",sep = "")
cat(as.character(left_factorial(n)))
cat("\n")
}
for (n in seq(20,110,10)) {
cat("!",n," = ",sep = "")
cat(as.character(left_factorial(n)))
cat("\n")
}
for (n in seq(1000,10000,1000)) {
cat("!",n," has ",digit_count(left_factorial(n))," digits\n", sep = "")
} | 652Left factorials
| 13r
| 3h4zt |
package main
import (
"fmt"
"math/big"
)
var (
p = map[int]int{1: 0}
lvl = [][]int{[]int{1}}
)
func path(n int) []int {
if n == 0 {
return []int{}
}
for {
if _, ok := p[n]; ok {
break
}
var q []int
for _, x := range lvl[0] {
for _, y := range path(x) {
z := x + y
if _, ok := p[z]; ok {
break
}
p[z] = x
q = append(q, z)
}
}
lvl[0] = q
}
r := path(p[n])
r = append(r, n)
return r
}
func treePow(x float64, n int) *big.Float {
r := map[int]*big.Float{0: big.NewFloat(1), 1: big.NewFloat(x)}
p := 0
for _, i := range path(n) {
temp := new(big.Float).SetPrec(320)
temp.Mul(r[i-p], r[p])
r[i] = temp
p = i
}
return r[n]
}
func showPow(x float64, n int, isIntegral bool) {
fmt.Printf("%d:%v\n", n, path(n))
f := "%f"
if isIntegral {
f = "%.0f"
}
fmt.Printf(f, x)
fmt.Printf(" ^%d = ", n)
fmt.Printf(f+"\n\n", treePow(x, n))
}
func main() {
for n := 0; n <= 17; n++ {
showPow(2, n, true)
}
showPow(1.1, 81, false)
showPow(3, 191, true)
} | 670Knuth's power tree
| 0go
| scbqa |
use strict;
use warnings;
use feature 'say';
sub kosaraju {
our(%k) = @_;
our %g = ();
our %h;
my $i = 0;
$g{$_} = $i++ for sort keys %k;
$h{$g{$_}} = $_ for keys %g;
our(%visited, @stack, @transpose, @connected);
sub visit {
my($u) = @_;
unless ($visited{$u}) {
$visited{$u} = 1;
for my $v (@{$k{$u}}) {
visit($v);
push @{$transpose[$g{$v}]}, $u;
}
push @stack, $u;
}
}
sub assign {
my($u, $root) = @_;
if ($visited{$u}) {
$visited{$u} = 0;
$connected[$g{$u}] = $root;
assign($_, $root) for @{$transpose[$g{$u}]};
}
}
visit($_) for sort keys %g;
assign($_, $_) for reverse @stack;
my %groups;
for my $i (0..$
my $id = $g{$connected[$i]};
push @{$groups{$id}}, $h{$i};
}
say join ' ', @{$groups{$_}} for sort keys %groups;
}
my %test1 = (
0 => [1],
1 => [2],
2 => [0],
3 => [1, 2, 4],
4 => [3, 5],
5 => [2, 6],
6 => [5],
7 => [4, 6, 7]
);
my %test2 = (
'Andy' => ['Bart'],
'Bart' => ['Carl'],
'Carl' => ['Andy'],
'Dave' => [<Bart Carl Earl>],
'Earl' => [<Dave Fred>],
'Fred' => [<Carl Gary>],
'Gary' => ['Fred'],
'Hank' => [<Earl Gary Hank>]
);
kosaraju(%test1);
say '';
kosaraju(%test2); | 665Kosaraju
| 2perl
| 4sv5d |
import java.util.Arrays;
public class Kolakoski {
private static class Crutch {
final int len;
int[] s;
int i;
Crutch(int len) {
this.len = len;
s = new int[len];
i = 0;
}
void repeat(int count) {
for (int j = 0; j < count; j++) {
if (++i == len) return;
s[i] = s[i - 1];
}
}
}
private static int nextInCycle(final int[] self, int index) {
return self[index % self.length];
}
private static int[] kolakoski(final int[] self, int len) {
Crutch c = new Crutch(len);
int k = 0;
while (c.i < len) {
c.s[c.i] = nextInCycle(self, k);
if (c.s[k] > 1) {
c.repeat(c.s[k] - 1);
}
if (++c.i == len) return c.s;
k++;
}
return c.s;
}
private static boolean possibleKolakoski(final int[] self) {
int[] rle = new int[self.length];
int prev = self[0];
int count = 1;
int pos = 0;
for (int i = 1; i < self.length; i++) {
if (self[i] == prev) {
count++;
} else {
rle[pos++] = count;
count = 1;
prev = self[i];
}
} | 663Kolakoski sequence
| 9java
| zjztq |
int main(int c, char *v[])
{
int days[] = {31,29,31,30,31,30,31,31,30,31,30,31};
int m, y, w;
if (c < 2 || (y = atoi(v[1])) <= 1700) return 1;
days[1] -= (y % 4) || (!(y % 100) && (y % 400));
w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6;
for(m = 0; m < 12; m++) {
w = (w + days[m]) % 7;
printf(, y, m + 1,
days[m] + (w < 5 ? -2 : 5) - w);
}
return 0;
} | 671Last Friday of each month
| 5c
| 9pnm1 |
package main
import (
"fmt"
"math/big"
)
func main() {
limit := 100
last := 12
unsigned := true
l := make([][]*big.Int, limit+1)
for n := 0; n <= limit; n++ {
l[n] = make([]*big.Int, limit+1)
for k := 0; k <= limit; k++ {
l[n][k] = new(big.Int)
}
l[n][n].SetInt64(int64(1))
if n != 1 {
l[n][1].MulRange(int64(2), int64(n))
}
}
var t big.Int
for n := 1; n <= limit; n++ {
for k := 1; k <= n; k++ {
t.Mul(l[n][1], l[n-1][1])
t.Quo(&t, l[k][1])
t.Quo(&t, l[k-1][1])
t.Quo(&t, l[n-k][1])
l[n][k].Set(&t)
if !unsigned && (n%2 == 1) {
l[n][k].Neg(l[n][k])
}
}
}
fmt.Println("Unsigned Lah numbers: l(n, k):")
fmt.Printf("n/k")
for i := 0; i <= last; i++ {
fmt.Printf("%10d ", i)
}
fmt.Printf("\n--")
for i := 0; i <= last; i++ {
fmt.Printf("-----------")
}
fmt.Println()
for n := 0; n <= last; n++ {
fmt.Printf("%2d ", n)
for k := 0; k <= n; k++ {
fmt.Printf("%10d ", l[n][k])
}
fmt.Println()
}
fmt.Println("\nMaximum value from the l(100, *) row:")
max := new(big.Int).Set(l[limit][0])
for k := 1; k <= limit; k++ {
if l[limit][k].Cmp(max) > 0 {
max.Set(l[limit][k])
}
}
fmt.Println(max)
fmt.Printf("which has%d digits.\n", len(max.String()))
} | 664Lah numbers
| 0go
| iu8og |
(defn maxcat [coll]
(read-string
(apply str
(sort (fn [x y]
(apply compare
(map read-string [(str y x) (str x y)])))
coll))))
(prn (map maxcat [[1 34 3 98 9 76 45 4] [54 546 548 60]])) | 666Largest int from concatenated ints
| 6clojure
| 3jdzr |
public class LynchBell {
static String s = "";
public static void main(String args[]) { | 661Largest number divisible by its digits
| 9java
| 8vi06 |
grouped = (1..13).to_a.repeated_permutation(3).group_by do |a,b,c|
sumaabb, ab = a*a + b*b, a*b
case c*c
when sumaabb then 90
when sumaabb - ab then 60
when sumaabb + ab then 120
end
end
grouped.delete(nil)
res = grouped.transform_values{|v| v.map(&:sort).uniq }
res.each do |k,v|
puts
puts v.inspect,
end | 655Law of cosines - triples
| 14ruby
| a6o1s |
typedef struct{
double x,y;
}point;
void kochCurve(point p1,point p2,int times){
point p3,p4,p5;
double theta = pi/3;
if(times>0){
p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
kochCurve(p1,p3,times-1);
kochCurve(p3,p4,times-1);
kochCurve(p4,p5,times-1);
kochCurve(p5,p2,times-1);
}
else{
line(p1.x,p1.y,p2.x,p2.y);
}
}
int main(int argC, char** argV)
{
int w,h,r;
point p1,p2;
if(argC!=4){
printf(,argV[0]);
}
else{
w = atoi(argV[1]);
h = atoi(argV[2]);
r = atoi(argV[3]);
initwindow(w,h,);
p1 = (point){10,h-10};
p2 = (point){w-10,h-10};
kochCurve(p1,p2,r);
getch();
closegraph();
}
return 0;
} | 672Koch curve
| 5c
| mboys |
(defn s-of-n-fn-creator [n]
(fn [[sample iprev] item]
(let [i (inc iprev)]
(if (<= i n)
[(conj sample item) i]
(let [r (rand-int i)]
(if (< r n)
[(assoc sample r item) i]
[sample i]))))))
(def s-of-3-fn (s-of-n-fn-creator 3))
(->> #(reduce s-of-3-fn [[] 0] (range 10))
(repeatedly 100000)
(map first)
flatten
frequencies
sort
println) | 669Knuth's algorithm S
| 6clojure
| z78tj |
class PowerTree {
private static Map<Integer, Integer> p = new HashMap<>()
private static List<List<Integer>> lvl = new ArrayList<>()
static {
p[1] = 0
List<Integer> temp = new ArrayList<Integer>()
temp.add 1
lvl.add temp
}
private static List<Integer> path(int n) {
if (n == 0) return new ArrayList<Integer>()
while (!p.containsKey(n)) {
List<Integer> q = new ArrayList<>()
for (Integer x in lvl.get(0)) {
for (Integer y in path(x)) {
if (p.containsKey(x + y)) break
p[x + y] = x
q.add x + y
}
}
lvl[0].clear()
lvl[0].addAll q
}
List<Integer> temp = path p[n]
temp.add n
temp
}
private static BigDecimal treePow(double x, int n) {
Map<Integer, BigDecimal> r = new HashMap<>()
r[0] = BigDecimal.ONE
r[1] = BigDecimal.valueOf(x)
int p = 0
for (Integer i in path(n)) {
r[i] = r[i - p] * r[p]
p = i
}
r[n]
}
private static void showPos(double x, int n, boolean isIntegral) {
printf("%d:%s\n", n, path(n))
String f = isIntegral ? "%.0f": "%f"
printf(f, x)
printf(" ^%d = ", n)
printf(f, treePow(x, n))
println()
println()
}
static void main(String[] args) {
for (int n = 0; n <= 17; ++n) {
showPos 2.0, n, true
}
showPos 1.1, 81, false
showPos 3.0, 191, true
}
} | 670Knuth's power tree
| 7groovy
| a3r1p |
int main(){
char input[100],output[100];
int i,j,k,l,rowA,colA,rowB,colB,rowC,colC,startRow,startCol;
double **matrixA,**matrixB,**matrixC;
printf();
fscanf(stdin,,input);
printf();
fscanf(stdin,,output);
FILE* inputFile = fopen(input,);
fscanf(inputFile,,&rowA,&colA);
matrixA = (double**)malloc(rowA * sizeof(double*));
for(i=0;i<rowA;i++){
matrixA[i] = (double*)malloc(colA*sizeof(double));
for(j=0;j<colA;j++){
fscanf(inputFile,,&matrixA[i][j]);
}
}
fscanf(inputFile,,&rowB,&colB);
matrixB = (double**)malloc(rowB * sizeof(double*));
for(i=0;i<rowB;i++){
matrixB[i] = (double*)malloc(colB*sizeof(double));
for(j=0;j<colB;j++){
fscanf(inputFile,,&matrixB[i][j]);
}
}
fclose(inputFile);
rowC = rowA*rowB;
colC = colA*colB;
matrixC = (double**)malloc(rowC*sizeof(double*));
for(i=0;i<rowA*rowB;i++){
matrixC[i] = (double*)malloc(colA*colB*sizeof(double));
}
for(i=0;i<rowA;i++){
for(j=0;j<colA;j++){
startRow = i*rowB;
startCol = j*colB;
for(k=0;k<rowB;k++){
for(l=0;l<colB;l++){
matrixC[startRow+k][startCol+l] = matrixA[i][j]*matrixB[k][l];
}
}
}
}
FILE* outputFile = fopen(output,);
for(i=0;i<rowC;i++){
for(j=0;j<colC;j++){
fprintf(outputFile,,matrixC[i][j]);
}
fprintf(outputFile,);
}
fclose(outputFile);
printf(,output);
} | 673Kronecker product
| 5c
| 4s35t |
null | 663Kolakoski sequence
| 11kotlin
| i5io4 |
import Text.Printf (printf)
import Control.Monad (when)
factorial :: Integral n => n -> n
factorial 0 = 1
factorial n = product [1..n]
lah :: Integral n => n -> n -> n
lah n k
| k == 1 = factorial n
| k == n = 1
| k > n = 0
| k < 1 || n < 1 = 0
| otherwise = f n `div` f k `div` factorial (n - k)
where
f = (*) =<< (^ 2) . factorial . pred
printLah :: (Word, Word) -> IO ()
printLah (n, k) = do
when (k == 0) (printf "\n%3d" n)
printf "%11d" (lah n k)
main :: IO ()
main = do
printf "Unsigned Lah numbers: L(n, k):\nn/k"
mapM_ (printf "%11d") zeroToTwelve
mapM_ printLah $ (,) <$> zeroToTwelve <*> zeroToTwelve
printf "\nMaximum value from the L(100, *) row:\n%d\n"
(maximum $ lah 100 <$> ([0..100] :: [Integer]))
where zeroToTwelve = [0..12] | 664Lah numbers
| 8haskell
| vwl2k |
null | 659Last letter-first letter
| 9java
| g8h4m |
def lpd(n):
for i in range(n-1,0,-1):
if n%i==0: return i
return 1
for i in range(1,101):
print(.format(lpd(i)), end=i%10==0 and '\n' or '') | 660Largest proper divisor of n
| 3python
| oud81 |
main() {
int x=8;
int y=12;
int z= gcd(x,y);
var lcm=(x*y)/z;
print('$lcm');
}
int gcd(int a,int b)
{
if(b==0)
return a;
if(b!=0)
return gcd(b,a%b);
} | 667Least common multiple
| 18dart
| ux9vs |
typealias F1 = (Int) -> [(Int, Int, Int)]
typealias F2 = (Int) -> Bool
func pythagoreanTriples(n: Int) -> [(Int, Int, Int)] {
(1...n).flatMap({x in
(x...n).flatMap({y in
(y...n).filter({z in
x * x + y * y == z * z
} as F2).map({ (x, y, $0) })
} as F1)
} as F1)
}
print(pythagoreanTriples(n: 20)) | 650List comprehensions
| 17swift
| 40x5g |
use strict;
package LCG;
use overload '0+' => \&get;
use integer;
sub gen_bsd { (1103515245 * shift() + 12345) % (1 << 31) }
sub gen_ms {
my $s = (214013 * shift() + 2531011) % (1 << 31);
$s, $s / (1 << 16)
}
sub set { $_[0]->{seed} = $_[1] }
sub get {
my $o = shift;
($o->{seed}, my $r) = $o->{meth}->($o->{seed});
$r //= $o->{seed}
}
sub new {
my $cls = shift;
my %opts = @_;
bless {
seed => $opts{seed},
meth => $opts{meth} eq 'MS' ? \&gen_ms : \&gen_bsd,
}, ref $cls || $cls;
}
package main;
my $rand = LCG->new;
print "BSD:\n";
print "$rand\n" for 1 .. 10;
$rand = LCG->new(meth => 'MS');
print "\nMS:\n";
print "$rand\n" for 1 .. 10; | 653Linear congruential generator
| 2perl
| caj9a |
module Rosetta.PowerTree
( Natural
, powerTree
, power
) where
import Data.Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import Data.List (foldl')
import Data.Sequence (Seq (..), (|>))
import qualified Data.Sequence as Seq
import Numeric.Natural (Natural)
type M = Map Natural S
type S = Seq Natural
levels:: [M]
levels = let s = Seq.singleton 1 in fst <$> iterate step (Map.singleton 1 s, s)
step:: (M, S) -> (M, S)
step (m, xs) = foldl' f (m, Empty) xs
where
f :: (M, S) -> Natural -> (M, S)
f (m', ys) n = foldl' g (m', ys) ns
where
ns:: S
ns = m' Map.! n
g :: (M, S) -> Natural -> (M, S)
g (m'', zs) k =
let l = n + k
in case Map.lookup l m'' of
Nothing -> (Map.insert l (ns |> l) m'', zs |> l)
Just _ -> (m'', zs)
powerTree :: Natural -> [Natural]
powerTree n
| n <= 0 = []
| otherwise = go levels
where
go :: [M] -> [Natural]
go [] = error "impossible branch"
go (m: ms) = fromMaybe (go ms) $ toList <$> Map.lookup n m
power :: forall a. Num a => a -> Natural -> a
power _ 0 = 1
power a n = go a 1 (Map.singleton 1 a) $ tail $ powerTree n
where
go :: a -> Natural -> Map Natural a -> [Natural] -> a
go b _ _ [] = b
go b k m (l: ls) =
let b' = b * m Map.! (l - k)
m' = Map.insert l b' m
in go b' l m' ls | 670Knuth's power tree
| 8haskell
| 9pdmo |
def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
nonlocal.x = nonlocal.x - 1
l[nonlocal.x] = u
for u in range(len(g)):
visit(u)
c = [0]*size
def assign(u, root):
if vis[u]:
vis[u] = False
c[u] = root
for v in t[u]:
assign(v, root)
for u in l:
assign(u, u)
return c
g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g) | 665Kosaraju
| 3python
| g0u4h |
function next_in_cycle(c,length,index)
local pos = index % length
return c[pos]
end
function kolakoski(c,s,clen,slen)
local i = 0
local k = 0
while true do
s[i] = next_in_cycle(c,clen,k)
if s[k] > 1 then
for j=1,s[k]-1 do
i = i + 1
if i == slen then
return nil
end
s[i] = s[i - 1]
end
end
i = i + 1
if i == slen then
return nil
end
k = k + 1
end
return nil
end
function possible_kolakoski(s,length)
local j = 0
local prev = s[0]
local count = 1
local rle = {}
local result = "True"
for i=0,length do
rle[i] = 0
end
for i=1,length-1 do
if s[i] == prev then
count = count + 1
else
rle[j] = count
j = j + 1
count = 1
prev = s[i]
end
end | 663Kolakoski sequence
| 1lua
| n4ni8 |
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class LahNumbers {
public static void main(String[] args) {
System.out.println("Show the unsigned Lah numbers up to n = 12:");
for ( int n = 0 ; n <= 12 ; n++ ) {
System.out.printf("%5s", n);
for ( int k = 0 ; k <= n ; k++ ) {
System.out.printf("%12s", lahNumber(n, k));
}
System.out.printf("%n");
}
System.out.println("Show the maximum value of L(100, k):");
int n = 100;
BigInteger max = BigInteger.ZERO;
for ( int k = 0 ; k <= n ; k++ ) {
max = max.max(lahNumber(n, k));
}
System.out.printf("%s", max);
}
private static Map<String,BigInteger> CACHE = new HashMap<>();
private static BigInteger lahNumber(int n, int k) {
String key = n + "," + k;
if ( CACHE.containsKey(key) ) {
return CACHE.get(key);
} | 664Lah numbers
| 9java
| yk36g |
const endsWith = word => word[word.length - 1];
const getCandidates = (words, used) => words.filter(e => !used.includes(e));
const buildLookup = words => {
const lookup = new Map();
words.forEach(e => {
const start = e[0];
lookup.set(start, [...(lookup.get(start) || []), e]);
});
return lookup;
};
const findPaths = names => {
const t0 = process.hrtime();
console.log('Checking:', names.length, 'names');
const lookup = buildLookup(names);
let maxNum = 0;
let maxPaths = [];
const parseResult = arr => {
if (typeof arr[0] === 'object') {
arr.forEach(el => parseResult(el))
} else {
if (arr.length > maxNum) {
maxNum = arr.length;
maxPaths = [arr];
}
if (arr.length === maxNum) {
maxPaths.push(arr)
}
}
};
const searchWords = (word, res) => {
const cs = getCandidates(lookup.get(endsWith(word)) || [], res);
return cs.length ? cs.map(e => searchWords(e, [...res, e])) : res;
};
names.forEach(word => {
const res = searchWords(word, [word]);
parseResult(res);
});
const t1 = process.hrtime(t0);
console.info('Execution time (hr):%ds%dms', t1[0], t1[1] / 1000000);
console.log('Max Path:', maxNum);
console.log('Matching Paths:', maxPaths.length);
console.log('Example Path:', maxPaths[0]);
};
const pokimon = ["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"];
findPaths(pokimon); | 659Last letter-first letter
| 10javascript
| kfahq |
null | 661Largest number divisible by its digits
| 11kotlin
| wmqek |
function isDivisible(n)
local t = n
local a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
while t ~= 0 do
local r = t % 10
if r == 0 then
return false
end
if n % r ~= 0 then
return false
end
if a[r + 1] > 0 then
return false
end
a[r + 1] = 1
t = math.floor(t / 10)
end
return true
end
for i=9999999999,0,-1 do
if isDivisible(i) then
print(i)
break
end
end | 661Largest number divisible by its digits
| 1lua
| x9swz |
largest_proper_divisor <- function(n){
if(n == 1) return(1)
lpd = 1
for(i in seq(1, n-1, 1)){
if(n%% i == 0)
lpd = i
}
message(paste0("The largest proper divisor of ", n, " is ", lpd))
return(lpd)
}
for (i in 1:100){
largest_proper_divisor(i)
} | 660Largest proper divisor of n
| 13r
| qc8xs |
left_fact = Enumerator.new do |y|
f, lf = 1, 0
1.step do |n|
y << lf
lf += f
f *= n
end
end | 652Left factorials
| 14ruby
| lekcl |
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PowerTree {
private static Map<Integer, Integer> p = new HashMap<>();
private static List<List<Integer>> lvl = new ArrayList<>();
static {
p.put(1, 0);
ArrayList<Integer> temp = new ArrayList<>();
temp.add(1);
lvl.add(temp);
}
private static List<Integer> path(int n) {
if (n == 0) return new ArrayList<>();
while (!p.containsKey(n)) {
List<Integer> q = new ArrayList<>();
for (Integer x : lvl.get(0)) {
for (Integer y : path(x)) {
if (p.containsKey(x + y)) break;
p.put(x + y, x);
q.add(x + y);
}
}
lvl.get(0).clear();
lvl.get(0).addAll(q);
}
List<Integer> temp = path(p.get(n));
temp.add(n);
return temp;
}
private static BigDecimal treePow(double x, int n) {
Map<Integer, BigDecimal> r = new HashMap<>();
r.put(0, BigDecimal.ONE);
r.put(1, BigDecimal.valueOf(x));
int p = 0;
for (Integer i : path(n)) {
r.put(i, r.get(i - p).multiply(r.get(p)));
p = i;
}
return r.get(n);
}
private static void showPow(double x, int n, boolean isIntegral) {
System.out.printf("%d:%s\n", n, path(n));
String f = isIntegral ? "%.0f" : "%f";
System.out.printf(f, x);
System.out.printf(" ^%d = ", n);
System.out.printf(f, treePow(x, n));
System.out.println("\n");
}
public static void main(String[] args) {
for (int n = 0; n <= 17; ++n) {
showPow(2.0, n, true);
}
showPow(1.1, 81, false);
showPow(3.0, 191, true);
}
} | 670Knuth's power tree
| 9java
| trsf9 |
package main
import "fmt"
type matrix [][]int
func (m1 matrix) kroneckerProduct(m2 matrix) matrix {
m := len(m1)
n := len(m1[0])
p := len(m2)
q := len(m2[0])
rtn := m * p
ctn := n * q
r := make(matrix, rtn)
for i := range r {
r[i] = make([]int, ctn) | 668Kronecker product based fractals
| 0go
| mbfyi |
sub kolakoski {
my($terms,@seed) = @_;
my @k;
my $k = $seed[0] == 1 ? 1 : 0;
if ($k == 1) { @k = (1, split //, (($seed[1]) x $seed[1])) }
else { @k = ($seed[0]) x $seed[0] }
do {
$k++;
push @k, ($seed[$k % @seed]) x $k[$k];
} until $terms <= @k;
@k[0..$terms-1]
}
sub rle {
(my $string = join '', @_) =~ s/((.)\2*)/length $1/eg;
split '', $string
}
for ([20,1,2], [20,2,1], [30,1,3,1,2], [30,1,3,2,1]) {
$terms = shift @$_;
print "\n$terms members of the series generated from [@$_] is:\n";
print join(' ', @kolakoski = kolakoski($terms, @$_)) . "\n";
$status = join('', @rle = rle(@kolakoski)) eq join('', @kolakoski[0..$
print "Looks like a Kolakoski sequence?: $status\n";
} | 663Kolakoski sequence
| 2perl
| rorgd |
(use '[clj-time.core:only [last-day-of-the-month day-of-week minus days]]
'[clj-time.format:only [unparse formatters]])
(defn last-fridays [year]
(let [last-days (map #(last-day-of-the-month year %) (range 1 13 1))
dow (map day-of-week last-days)
relation (zipmap last-days dow)]
(map #(minus (key %) (days (mod (+ (val %) 2) 7))) relation)))
(defn last-fridays-formatted [year]
(sort (map #(unparse (formatters:year-month-day) %) (last-fridays year)))) | 671Last Friday of each month
| 6clojure
| ux3vi |
#[cfg(target_pointer_width = "64")]
type USingle = u32;
#[cfg(target_pointer_width = "64")]
type UDouble = u64;
#[cfg(target_pointer_width = "64")]
const WORD_LEN: i32 = 32;
#[cfg(not(target_pointer_width = "64"))]
type USingle = u16;
#[cfg(not(target_pointer_width = "64"))]
type UDouble = u32;
#[cfg(not(target_pointer_width = "64"))]
const WORD_LEN: i32 = 16;
use std::cmp;
#[derive(Debug,Clone)]
struct BigNum { | 652Left factorials
| 15rust
| 2wblt |
<?php
function bsd_rand($seed) {
return function() use (&$seed) {
return $seed = (1103515245 * $seed + 12345) % (1 << 31);
};
}
function msvcrt_rand($seed) {
return function() use (&$seed) {
return ($seed = (214013 * $seed + 2531011) % (1 << 31)) >> 16;
};
}
$lcg = bsd_rand(0);
echo ;
for ($i = 0; $i < 10; $i++)
echo $lcg(), ;
echo ;
$lcg = msvcrt_rand(0);
echo ;
for ($i = 0; $i < 10; $i++)
echo $lcg(), ;
echo ;
?> | 653Linear congruential generator
| 12php
| x9tw5 |
import Reflex
import Reflex.Dom
import Data.Map as DM (Map, fromList)
import Data.Text (Text, pack)
import Data.List (transpose)
main :: IO ()
main = mainWidget $ do
elAttr "h1" ("style" =: "color:black") $ text "Kroneker Product Based Fractals"
elAttr "a" ("href" =: "http://rosettacode.org/wiki/Kronecker_product_based_fractals#Haskell") $ text "Rosetta Code / Kroneker product based fractals / Haskell"
el "br" $ return ()
elAttr "h2" ("style" =: "color:brown") $ text "Vicsek Fractal"
showFractal [[0, 1, 0] ,[1, 1, 1] ,[0, 1, 0] ]
el "br" $ return ()
elAttr "h2" ("style" =: "color:brown") $ text "Sierpinski Carpet Fractal"
showFractal [[1, 1, 1] ,[1, 0, 1] ,[1, 1, 1] ]
cellSize :: Int
cellSize = 8
showFractal :: MonadWidget t m => [[Int]] -> m ()
showFractal seed = do
let boardAttrs w h =
fromList [ ("width" , pack $ show $ w * cellSize)
, ("height", pack $ show $ h * cellSize)
]
fractals = iterate (kronekerProduct seed) seed
shown = fractals !! 3
w = length $ head shown
h = length shown
elSvgns "svg" (constDyn $ boardAttrs w h) $ showMatrix shown
kronekerProduct :: Num a => [[a]] -> [[a]] -> [[a]]
kronekerProduct xs ys =
let m0 = flip $ fmap.fmap.(*)
m1 = flip $ fmap.fmap.m0
in concat $ fmap (fmap concat.transpose) $ m1 xs ys
showMatrix :: MonadWidget t m => [[Int]] -> m ()
showMatrix m = mapM_ showRow $ zip [0..] m
showRow :: MonadWidget t m => (Int,[Int]) -> m ()
showRow (x,r) = mapM_ (showCell x) $ zip [0..] r
showCell :: MonadWidget t m => Int -> (Int,Int) -> m ()
showCell x (y,on) =
let boxAttrs (x,y) =
fromList [ ("transform",
pack $ "scale (" ++ show cellSize ++ ", " ++ show cellSize ++ ") "
++ "translate (" ++ show x ++ ", " ++ show y ++ ")"
)
]
cellAttrs =
fromList [ ( "cx", "0.5")
, ( "cy", "0.5")
, ( "r", "0.45")
, ( "style", "fill:green")
]
in if (on==1) then
elSvgns "g" (constDyn $ boxAttrs (x,y)) $
elSvgns "circle" (constDyn $ cellAttrs) $
return ()
else
return ()
elSvgns :: MonadWidget t m => Text -> Dynamic t (Map Text Text) -> m a -> m a
elSvgns t m ma = do
(el, val) <- elDynAttrNS' (Just "http://www.w3.org/2000/svg") t m ma
return val | 668Kronecker product based fractals
| 8haskell
| kd4h0 |
import java.math.BigInteger
fun factorial(n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) return BigInteger.ONE
if (n == BigInteger.ONE) return BigInteger.ONE
var prod = BigInteger.ONE
var num = n
while (num > BigInteger.ONE) {
prod *= num
num--
}
return prod
}
fun lah(n: BigInteger, k: BigInteger): BigInteger {
if (k == BigInteger.ONE) return factorial(n)
if (k == n) return BigInteger.ONE
if (k > n) return BigInteger.ZERO
if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO
return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k)
}
fun main() {
println("Unsigned Lah numbers: L(n, k):")
print("n/k ")
for (i in 0..12) {
print("%10d ".format(i))
}
println()
for (row in 0..12) {
print("%-3d".format(row))
for (i in 0..row) {
val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong()))
print("%11d".format(l))
}
println()
}
println("\nMaximum value from the L(100, *) row:")
println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max())
} | 664Lah numbers
| 11kotlin
| fgndo |
null | 659Last letter-first letter
| 11kotlin
| 2w4li |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.