testing1/collatz.scala
changeset 199 54befaf23648
parent 197 c3e39fdeea3b
child 281 87b9e3e2c1a7
equal deleted inserted replaced
198:d59c7995bcb2 199:54befaf23648
     1 // Part 1 about the 3n+1 conjecture
     1 // Part 1 about the 3n+1 conjecture
     2 //==================================
     2 //==================================
     3 package CW6a 
       
     4 
     3 
     5 
     4 
     6 object CW6a {
     5 //object CW6a { // for purposes of generating a jar
     7 
     6 
     8 def collatz(n: Long): Long =
     7 def collatz(n: Long): Long =
     9   if (n == 1) 1 else
     8   if (n == 1) 0 else
    10     if (n % 2 == 0) 1 + collatz(n / 2) else 
     9     if (n % 2 == 0) 1 + collatz(n / 2) else 
    11       1 + collatz(3 * n + 1)
    10       1 + collatz(3 * n + 1)
    12 
    11 
    13 
    12 
    14 def collatz_max(bnd: Long): (Long, Long) = {
    13 def collatz_max(bnd: Long): (Long, Long) = {
    15   val all = for (i <- (1 to bnd.toInt).toList) yield collatz(i)
    14   val all = for (i <- (1L to bnd)) yield (collatz(i), i)
    16   val max = all.max
    15   all.maxBy(_._1)
    17   (max, all.indexOf(max) + 1)
       
    18 }
    16 }
    19 
    17 
       
    18 /* some test cases
       
    19 val bnds = List(10, 100, 1000, 10000, 100000, 1000000)
    20 
    20 
       
    21 for (bnd <- bnds) {
       
    22   val (steps, max) = collatz_max(bnd)
       
    23   println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}")
    21 }
    24 }
    22 
    25 
       
    26 */
    23 
    27 
    24 
    28 //}
    25 (1 to 10).map(collatz(_))