Skip to content

Instantly share code, notes, and snippets.

@gzoritchak
Last active March 7, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gzoritchak/1e2ec8d38fc39a4485ba to your computer and use it in GitHub Desktop.
Save gzoritchak/1e2ec8d38fc39a4485ba to your computer and use it in GitHub Desktop.
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