Last active
August 29, 2015 14:09
-
-
Save siosio/fe2b85468f1807576efd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package collatz | |
import kotlin.util.measureTimeMillis | |
import java.util.HashMap | |
import java.util.Arrays | |
val MAX = 100000 | |
fun main(args: Array<String>) { | |
println(measureTimeMillis { | |
println((2..MAX).map { Pair(it, calc(it)) }.maxBy { it.second }) | |
}) | |
} | |
val step = StepCache(MAX) | |
fun calc(i: Int): Int { | |
val cashed = step.get(i) | |
return if (cashed != 0) { | |
cashed | |
} else { | |
val next = next(i) | |
if (next == 1) { | |
next | |
} else { | |
return step.put(i, calc(next) + 1) | |
} | |
} | |
} | |
class StepCache(val size: Int) { | |
val cache = IntArray(size * 1000); | |
{ | |
var count = 0; | |
stream(2, { it shl 1 }) | |
.takeWhile { it <= size } | |
.forEach { count++; cache[it] = count } | |
} | |
fun get(i: Int): Int { | |
return if (i > size) { | |
0 | |
} else { | |
cache[i] | |
} | |
} | |
fun put(i:Int, step:Int):Int { | |
if (i > size) { | |
return step | |
} | |
cache[i] = step | |
return step | |
} | |
} | |
fun next(i: Int): Int { | |
return if ((i and 0x01) == 0 ) { | |
i / 2 | |
} else { | |
i * 3 + 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(77031, 350)
239ms