Created
October 6, 2016 11:47
-
-
Save mnd999/4c07ef357914444b120aebc05d13dfab to your computer and use it in GitHub Desktop.
Recursive scala implementation of Towers of Hanoi
This file contains hidden or 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
import scala.collection.immutable._ | |
object TowersOfHanoi extends App { | |
case class State(a : Seq[Int], b: Seq[Int], c: Seq[Int]) | |
val discs = 8 | |
val state = State(0 to discs, List[Int](), List[Int]()); | |
def moveTower(disc: Int, state: State) : State = { | |
val newState = if (disc == 0) { | |
State(state.a.tail, 0 +: state.b, state.c) | |
} else { | |
val i1 = moveTower(disc - 1, State(state.a, state.c, state.b)) | |
val i2 = State(i1.a.tail, disc +: i1.c, i1.b) | |
val i3 = moveTower(disc - 1, State(i2.c, i2.b, i2.a)) | |
State(i3.c, i3.b, i3.a) | |
} | |
newState | |
} | |
println(moveTower(discs, state)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment