progs/lecture2.scala
changeset 309 b192bc772613
parent 278 0c2481cd8b1c
child 310 335079d938aa
equal deleted inserted replaced
308:e86add5a6961 309:b192bc772613
   523   case s"$day/$month/$year" => Some((year.toInt, month.toInt, day.toInt))
   523   case s"$day/$month/$year" => Some((year.toInt, month.toInt, day.toInt))
   524   case _ => None
   524   case _ => None
   525 } 
   525 } 
   526 
   526 
   527 
   527 
       
   528 // Recursion
       
   529 //===========
       
   530 
       
   531 /* a, b, c
       
   532 
       
   533 aa         aaa
       
   534 ab         baa 
       
   535 ac         caa 
       
   536 ba  =>     ......
       
   537 bb
       
   538 bc
       
   539 ca
       
   540 cb
       
   541 cc
       
   542 
       
   543 */
       
   544 
       
   545 def perms(cs: List[Char], l: Int) : List[String] = {
       
   546   if (l == 0) List("")
       
   547   else for (c <- cs; s <- perms(cs, l - 1)) yield s"$c$s"
       
   548 }
       
   549 
       
   550 perms("abc".toList, 2)
       
   551 
       
   552 def move(from: Char, to: Char) =
       
   553   println(s"Move disc from $from to $to!")
       
   554 
       
   555 def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
       
   556   if (n == 0) ()
       
   557   else {
       
   558     hanoi(n - 1, from, to, via)
       
   559     move(from, to)
       
   560     hanoi(n - 1, via, from, to)
       
   561   }
       
   562 } 
       
   563 
       
   564 hanoi(40, 'A', 'B', 'C')
       
   565 
       
   566 
   528 // Tail Recursion
   567 // Tail Recursion
   529 //================
   568 //================
   530 
   569 
   531 
   570 
   532 def fact(n: Long): Long = 
   571 def fact(n: Long): Long =