Created
January 15, 2015 21:42
-
-
Save cjavdev/5bd2f6b0400d96f201da to your computer and use it in GitHub Desktop.
Towers of Hanoi in scala
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
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[Bug Fix] Change line 37 to: towers(from).length > 0 && (towers(to).length == 0 || towers(from).head < towers(to).head)