Skip to content

Instantly share code, notes, and snippets.

@cjavdev
Created January 15, 2015 21:42
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 cjavdev/5bd2f6b0400d96f201da to your computer and use it in GitHub Desktop.
Save cjavdev/5bd2f6b0400d96f201da to your computer and use it in GitHub Desktop.
Towers of Hanoi in scala
class TowersOfHanoi {
def Play(towers: List[List[Int]] = List(List(1, 2, 3), List[Int](), List[Int]())) {
Display(towers)
if(GameOver(towers)) {
println("You win!")
return
}
val from = GetMoveTower("Pick a from tower");
val to = GetMoveTower("Pick a to tower");
val moveResult = Move(from, to, towers)
Play(moveResult)
}
def Move(from: Int, to: Int, towers: List[List[Int]]): List[List[Int]] = {
if(!CanMove(from, to, towers)) {
println("Can't move there")
return towers
}
val disk = towers(from).head
var i = 0;
towers.foldLeft(List[List[Int]]())((r, l) =>
if (i == from) {
i += 1;
r ::: List(l.tail);
} else if (i == to) {
i+= 1;
r ::: List(List(disk) ::: l);
} else {
i+= 1;
r ::: List(l);
}
)
}
def CanMove(from: Int, to: Int, towers: List[List[Int]]): Boolean = {
towers(to).length == 0 || towers(from).head < towers(to).head
}
def GameOver(towers: List[List[Int]]) : Boolean = {
towers(0).length == 0 && towers(2).length == 3
}
def Display(towers: List[List[Int]]) {
println(towers(0));
println(towers(1));
println(towers(2));
}
def GetMoveTower(message: String) : Int = {
println(message)
readInt
}
}
val game = new TowersOfHanoi()
game.Play()
@Dmyan
Copy link

Dmyan commented Jul 26, 2016

[Bug Fix] Change line 37 to: towers(from).length > 0 && (towers(to).length == 0 || towers(from).head < towers(to).head)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment