Home Blog Towers of Hanoi in Scala
 

Why?  Why not!

Source of hanoi.scala

object Hanoi {
  def main (args: Array[String]) : Unit = {
    var plates: Int = 4
    
    for { j <- args } plates = try { Integer.parseInt(j) } catch { case _ => 1 }
    val soln = hanoi(plates, "A", "C", "B")
    for { i <- soln }  Console.println(i)
  }

  def hanoi(n: Int, peg1: String, peg3: String, peg2: String) : List[String] = {
    n match {
      case 1 => List( "Move the plate from " + peg1 + " to " + peg3)
      case _ => hanoi(n - 1, peg1, peg2, peg3) :::
        List( "Move the plate from "+ peg1 + " to "+ peg3) :::
        hanoi(n - 1, peg2, peg3, peg1)
    }
  }
}

Compile and invoke as "scala Hanoi" or "scala Hanoi x" where x is the number of plates to solve.

Blog Navigation

The Latest

Scala on .NET

Posted by Eric Somdahl in Blog Entries

Towers of Hanoi in Scala

Posted by Eric Somdahl in Uncategorized
Joomla Templates by Joomlashack