K 99: Ninety Nine K Problems - kevinlawler/kona GitHub Wiki
K translation of Ninety-Nine Prolog Problems
Find the last element of a list.last "abcdef" "f"
last : *|: / reverse, take first last2: {x@-1+#x} / index at length-1 last3: {:[1=#x;x;_f 1_ x]} last4: {-1#x} / take 1 from endFind the last but one element of a list.
butlast "abcdef" "e"
butlast : {(|x)@1} butlast2: {x@-2+#x} butlast3: {:[2=#x;*x;_f 1_ x]} butlast4: *-2!Find the K'th element of a list.
elementat["abcdef";3] "c"
elementat : {x@y-1} elementat2: {*(y-1)(1_)/x} elementat2: {:[y=1;*x;_f[1_ x;y-1]]}Find the number of elements of a list.
length 1 2 3 4 4
length : #: length2: {+/*:'1,'x}Reverse a list.
reverse "abcdef" "fedcba"
reverse : |: reverse2: {x@(-1+l)-!l:#x} reverse3: {:[1=#x;x;_f[1_ x],*x]}Find out whether a list is a palindrome.
ispalindrome "aacbcaa" 1
ispalindrome: {x~|x}Flatten a nested list structure.
flatten ((1;2 3);(4;(5;(6;7)));8) 1 2 3 4 5 6 7 8
flatten: ,//Eliminate consecutive duplicates of list elements.
compress "aaaabccaadeeee" "abcade"
compress : {x@&1,~=':x} range : ? / built in operatorPack consecutive duplicates of list elements into sublists.
pack "aaaabccaadeeee" ("aaaa" ,"b" "cc" "aa" ,"d" "eeee")
pack: {(&1,~=':x)_ x}Run-length encoding of a list.
encode "aaaabccaadeeee" ((4;"a") (1;"b") (2;"c") (2;"a") (1;"d") (4;"e"))
encode : {(#:;*:)@\:/:pack x} encode2: {(#:'a),'*:'a:pack x}Modified run-length encoding.
encodemod "aaaabccaadeeee" ((4;"a") ,"b" (2;"c") (2;"a") ,"d" (4;"e"))
encodemod: {{:[1=l:#x;x;l,?x]}'pack x}Decode a run-length encoded list.
decodemod ((4;"a");"b";(2;"c");(2;"a");"d";(4;"e")) "aaaabccaadeeee"
decodemod: ,/{:[2=#x;(*x)#x@1;x]}' decodemod2: ,/#/'Run-length encoding of a list (direct solution).
Don't explicitly create the sublists containing the duplicates, only count them.
encodedir "aaaabccaadeeee" ((4;"a") ,"b" (2;"c") (2;"a") ,"d" (4;"e"))
encodedir: {(-':a,#x),'x@a:&1,~=':x}Duplicate the elements of a list.
dupl "abccd" "aabbccccdd"
dupl : ,/2#' dupl2: ,/{x,x}'Duplicate the elements of a list a given number of times.
repl["abccd";3] "aaabbbccccccddd"
repl: {,/y#'x}Drop every N'th element from a list.
dropevery["abcdefghij";3] "abdeghj"
dropevery : {x@&~(#x)#((y-1)#0),1} dropevery2: {x _di-1+y*1+!(#x)%y}Split a list into two parts; the length of the first part is given.
Do not use any predefined predicates.
split["abcdefghij";3] ("abc" "defghij")
split : {(y#x;y _ x)} split2: {(0,y)_ x} split3: {(x@!y;x@y+!(#x)-y)}Extract a slice from a list.
slice["abcdefghij";3;7] "cdef"
slice : {(y-1)_(z-1)#x} slice2: {x@(y-1)+!z-y}Rotate a list N places to the left.
rotate["abcdefghij";3] "defghijabc"
rotate : {y!x} rotate2: {,/(y>0)|:/split[x;y]}Remove the K'th element from a list.
removeat["abcdef";3] ("c" "abdef")
removeat : {(x@y;x _di y:y-1)} removeat2: {(x@i;x@&~x=x@i:y-1)}Insert an element at a given position into a list.
insert["abcd";2;"alfa"] ("a" "alfa" "b" "c" "d")
insert : {(l#x),(,z),(l:y-1)_ x} insert2: {(*s),(,z),,/1_ s:split[x;y]} insert3: {{x,(,z),y}/split[x;y]} insert4: {:[y=1;(,z),x;(*x),_f[1_ x;y-1;z]]}Create a list containing all integers within a given range.
range[3;7] 3 4 5 6 7 range[9;3] 9 8 7 6 5 4 3
range: {x+:[0>y-x;-1;1]*!1+_abs y-x} range: {:[x>y;|y+!x-y-1;x+!y-x-1]}Extract a given number of randomly selected elements from a list.
rndselect["abcdefgh";3] "bfe"
rndselect:{x@y _draw -#x}Lotto: Draw N different random numbers from the set 1..M.
lotto[6;49] 12 34 15 31 29 22
lotto : {(-x)?y} lotto2: {x _draw -y}Generate a random permutation of the elements of a list.
rndperm["abcdef"] "efbadc"
rndperm:{x@l _draw -l:#x}Generate the combinations of K distinct objects chosen from the N elements of a list.
combin["abcdef";3] ("abc" "abd" "abe" "abf" ... "def")
combin: {x@<x:x@{&:'y(?,/(1!)\'1,')/,&x-y}[#x;y]}Group the elements of a set into disjoint subsets.
list:("aldo";"beat";"carla";"david";"evi";"flip";"gary";"hugo";"ida") group[list;3] (("evi" "flip" "ida") ("evi" "flip" "gary") ...)
group: {combin[x;]'y}Sorting a list of lists according to length of sublists.
lsort[("abc";"de";"fgh";"de";"ijkl";"mn";"o")] ("o" "de" "de" "mn" "abc" "fgh" "ijkl")
lsort: {x@<#:'x}Sorting a list of lists according to length frequency of sublists.
lfsort[("abc";"de";"fgh";"de";"ijkl";"mn";"o")] ("ijkl" "o" "abc" "fgh" "de" "de" "mn")
lfsort: {x@,/f@<f:=#:'x}Determine whether a given integer number is prime.
isprime ' 0 1 2 4 5 0 0 1 0 1
isprime: {2~#&~x!'!1+x}Determine the prime factors of a given positive integer.
primefactors 315 3 3 5 7
primefactors: {{y%x}':({x>1}{x%*{1_ &~(x!)'!1+x}x}\x)}Construct a list containing the prime factors and their multiplicity.
multiplicity 315 (2 3 1 5 1 7)
multiplicity: {encode primefactors x}Given a range of integers by its lower and upper limit, construct a list of all prime numbers in that range.
primes[2;25] 2 3 5 7 11 13 17 19 23
primes: {x+&isprime'x+!1+y-x}Goldbach's conjecture says that every positive even number greater than 2 is the sum of two prime numbers. Example: 28 = 5 + 23. It is one of the most famous facts in number theory that has not been proved to be correct in the general case. Find the two prime numbers that sum up to a given even integer.
goldbach 28 5 23
ppairs: {,/t,/:\:t:primes[2;x]} goldbach: {*t@&{x=+/y}[x]'t:ppairs[x]}Given a range of integers by its lower and upper limit, print a list of all even numbers and their Goldbach composition.
goldbachc[9;20] (10 3 7 12 5 7 14 3 11 16 3 13 18 5 13 20 3 17)
evens: {2*((x+1)%2)+!(1+y-x)%2} goldbachc: {{x,goldbach x}'evens[x;y]}Determine the greatest common divisor of two positive integer numbers.
gcd[36;63] 9
gcd: {:[y;_f[y;x!y];x]}Determine whether two positive integer numbers are coprime. Two numbers are coprime if their greatest common divisor equals 1.
coprime[35;64] 1 coprime[35;63] 0
coprime: {1=gcd[x;y]}Calculate Euler's totient function phi(m). Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r < m) that are coprime to m.
phi 10 4
phi: {+/coprime[x]'!x}Calculate Euler's totient function phi(m)(2). If the list of the prime factors of a number m is known in the form of problem 2.03 then the function phi(m) can be efficiently calculated as follows: Let [[m1,p1],[m2,p2],[m3,p3],...] be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula:
phi(m) = (p1 - 1) * p1^(m1 - 1) * (p2 - 1) * p2^(m2 - 1) * (p3 - 1) * p3^(m3 - 1) * ...
phi2 10 4
phi2: {*/{(y-1)*y^x-1}.'multiplicity x};Compare the two methods of calculating Euler's totient function.
\t phi 10090 806 \t phi2 10090 7