Skip to content
Permalink
Browse files

Add Collatz sample

  • Loading branch information
thesephist committed Jan 29, 2020
1 parent e989618 commit 2b0ad9d453fbe882fc0222e5d7b6f921bbc16272
Showing with 42 additions and 0 deletions.
  1. +1 −0 Makefile
  2. +41 −0 samples/collatz.ink
@@ -13,6 +13,7 @@ run:
./ink samples/kv.ink
./ink samples/html.ink
./ink samples/fib.ink
./ink samples/collatz.ink
./ink samples/newton.ink
./ink samples/pi.ink
./ink samples/prime.ink
@@ -0,0 +1,41 @@
` finding long collatz sequences `

std := load('std')

log := std.log
f := std.format
sList := std.stringList

next := n => n % 2 :: {
0 -> n / 2
1 -> 3 * n + 1
}

sequence := start => start < 1 :: {
true -> []
false -> (sub := (n, acc) => n :: {
1 -> acc
_ -> sub(nx := next(n), acc.len(acc) := nx)
})(start, [start])
}

longestSequenceUnder := max => (sub := (n, prevMax, prevSeq) => n :: {
max -> prevSeq
_ -> (
currSeq := sequence(n)
currMax := len(currSeq)
currMax > prevMax :: {
true -> sub(n + 1, currMax, currSeq)
false -> sub(n + 1, prevMax, prevSeq)
}
)
})(1, 0, [])

` run a search for longest collatz sequence under Max `
Max := 1000
longest := longestSequenceUnder(Max)
log(f('Longest collatz seq under {{ max }} is {{ len }} items', {
max: Max
len: len(longest)
}))
log(sList(longest))

0 comments on commit 2b0ad9d

Please sign in to comment.
You can’t perform that action at this time.