progs/collatz_sol.scala
changeset 18 87e55eb309ed
parent 17 ecf83084e41d
child 24 66b97f9a40f8
equal deleted inserted replaced
17:ecf83084e41d 18:87e55eb309ed
    22 
    22 
    23 
    23 
    24 //(2)  Complete the collatz bound function below. It should
    24 //(2)  Complete the collatz bound function below. It should
    25 //     calculuate how many steps are needed for each number 
    25 //     calculuate how many steps are needed for each number 
    26 //     from 1 upto a bound and return the maximum number of
    26 //     from 1 upto a bound and return the maximum number of
       
    27 //     steps and the corresponding number that needs that many 
    27 //     steps. You should expect bounds in the range of 1
    28 //     steps. You should expect bounds in the range of 1
    28 //     upto 10 million. 
    29 //     upto 1 million. 
    29 
    30 
    30 def collatz_max(bnd: Int): Int = {
    31 def collatz_max(bnd: Int): (Int, Int) = {
    31   (for (i <- 1 to bnd) yield collatz(i).length).max
    32   val all = for (i <- (1 to bnd).toList) yield collatz(i).length
       
    33   val max = all.max
       
    34   (all.indexOf(max) + 1, max)
    32 }
    35 }
    33 
    36 
    34 
    37 
    35 // some testing harness
    38 // some testing harness
    36 val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000)
    39 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    37 
    40 
    38 for (bnd <- bnds) {
    41 for (bnd <- bnds) {
    39   val max = collatz_max(bnd)
    42   val (max, steps) = collatz_max(bnd)
    40   println(s"In the range of 1 - ${bnd} the maximum steps are ${max}")
    43   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    41 }
    44 }
    42 
    45 
       
    46 
       
    47 //val all = for (i <- (1 to 100000).toList) yield collatz1(i)
       
    48 //println(all.sorted.reverse.take(10))