Skip to content

Instantly share code, notes, and snippets.

@siosio
Last active August 29, 2015 14:09
Show Gist options
  • Save siosio/fe2b85468f1807576efd to your computer and use it in GitHub Desktop.
Save siosio/fe2b85468f1807576efd to your computer and use it in GitHub Desktop.
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
}
}
@siosio
Copy link
Author

siosio commented Nov 15, 2014

(77031, 350)
239ms

@siosio
Copy link
Author

siosio commented Nov 28, 2014

(77031, 350)
21ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment