Skip to content

Instantly share code, notes, and snippets.

@gzoritchak gzoritchak/Josephus.kt
Last active Mar 7, 2016

Embed
What would you like to do?
Josephus problem in Kotlin
data class Soldier(val position: Int, var state:State = State.Living) {
fun suicide() {
state = State.Dead
}
fun isAlive() = state == State.Living
}
enum class State {
Living, Dead
}
class DeathCircle(val size: Int, val step: Int) {
val soldiers = Array( size, {Soldier(it)}).toList()
fun findSurvivor(): Soldier {
var soldier = soldiers.first()
(2..size).forEach {
(1..step).forEach {
soldier = soldier.nextLivingSoldier()
}
soldier.suicide()
}
return soldier.nextLivingSoldier()
}
tailrec fun Soldier.nextLivingSoldier():Soldier =
if (next().isAlive())
next()
else
next().nextLivingSoldier()
fun Soldier.next() = soldiers.get(
if (position == size - 1)
0
else
position + 1
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.