Saturday, November 13, 2010

S24

S-99: Ninety-Nine Scala Problemsを試してみる。
勉強のためにListのAPIはなるべく使わない方向。

  1. // P24 (*) Lotto: Draw N different random numbers from the set 1..M.  
  2. // Example:  
  3. // scala> lotto(6, 49)  
  4. // res0: List[Int] = List(23, 1, 17, 33, 21, 37)  
  5.   
  6. import scala.util.Random  
  7. def lotto(n: Int, to: Int) = {  
  8.   val rand = new Random()  
  9.   def r(acc: List[Int]): List[Int] = {  
  10.     def next(): Int = {  
  11.       val i = rand.nextInt(to)  
  12.       if(acc.count(_ == i) == 0) i else next  
  13.     }  
  14.     if(acc.size < n) r(next :: acc) else acc  
  15.   }  
  16.   if(n < 1 || to < n) throw new IllegalArgumentException  
  17.   else r(Nil)  
  18. }  
解答例
こりゃ一本とられたわい

No comments:

Post a Comment