Skip to content

Instantly share code, notes, and snippets.

@alexmelyon
Last active December 18, 2018 23:30
Show Gist options
  • Save alexmelyon/ab0f88d21fdb415584b758fb0b6da1bc to your computer and use it in GitHub Desktop.
Save alexmelyon/ab0f88d21fdb415584b758fb0b6da1bc to your computer and use it in GitHub Desktop.
data class Variant(val step: Int, val Nheads: Int, val Mtails: Int, val comment: String = "", val prev: Variant? = null)
fun main(args: Array<String>) {
val variants = mutableListOf<Variant>()
variants.add(Variant(step = 0, Nheads = 3, Mtails = 1))
var i = 0
val max = 10
var result: Variant? = null
val isSwordBroken = true
while (variants[i].step <= max) {
val current = variants[i]
val extraTail = if(isSwordBroken && (current.step + 1) % 3 == 0) 1 else 0
// 1 tail produces 2 tails
if(current.Mtails >= 1) {
val next = Variant(current.step + 1, current.Nheads, current.Mtails + 1 + extraTail, "1 tail", current)
if (checkVariant(next, extraTail)) {
result = next
break
}
variants.add(next)
}
// 2 tails produces 1 head
if (current.Mtails >= 2) {
val next = Variant(current.step + 1, current.Nheads + 1, current.Mtails - 2 + extraTail, "2 tails", current)
if (checkVariant(next, extraTail)) {
result = next
break
}
variants.add(next)
}
// 1 head produces 1 head
if(isSwordBroken && current.Nheads >= 1) {
val next = Variant(current.step, current.Nheads, current.Mtails + extraTail, "1 heads", current)
if (checkVariant(next, extraTail)) {
result = next
break
}
variants.add(next)
}
// 2 heads produces nothing
if(current.Nheads >= 2) {
val next = Variant(current.step + 1, current.Nheads - 2, current.Mtails + extraTail, "2 heads", current)
if (checkVariant(next, extraTail)) {
result = next
break
}
variants.add(next)
}
i++
}
while (result != null) {
println(result.let { Variant(it.step, it.Nheads, it.Mtails, it.comment) })
result = result.prev
}
}
fun checkVariant(variant: Variant, extraTail: Int): Boolean {
return variant.Nheads == 0 && variant.Mtails == 0 && extraTail == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment