Last active
March 7, 2016 19:54
-
-
Save gzoritchak/1e2ec8d38fc39a4485ba to your computer and use it in GitHub Desktop.
Josephus problem in Kotlin
This file contains 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
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