勉強のためにListのAPIはなるべく使わない方向。
- // P24 (*) Lotto: Draw N different random numbers from the set 1..M.
- // Example:
- // scala> lotto(6, 49)
- // res0: List[Int] = List(23, 1, 17, 33, 21, 37)
- import scala.util.Random
- def lotto(n: Int, to: Int) = {
- val rand = new Random()
- def r(acc: List[Int]): List[Int] = {
- def next(): Int = {
- val i = rand.nextInt(to)
- if(acc.count(_ == i) == 0) i else next
- }
- if(acc.size < n) r(next :: acc) else acc
- }
- if(n < 1 || to < n) throw new IllegalArgumentException
- else r(Nil)
- }
こりゃ一本とられたわい
No comments:
Post a Comment