# HG changeset patch # User Christian Urban # Date 1479251092 0 # Node ID 70306f6c65b1530db51273ca9a05773fb5c2e6a8 # Parent 48d2cbe8ee5e3d70d7a61f4523d632a6066fb3fd updated diff -r 48d2cbe8ee5e -r 70306f6c65b1 TAs --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TAs Tue Nov 15 23:04:52 2016 +0000 @@ -0,0 +1,14 @@ + daniil.baryshnikov@kcl.ac.uk, + andrew.coles@kcl.ac.uk, + oliver.hohn@kcl.ac.uk, + fahad.ausaf@icloud.com, + fares.alaboud@kcl.ac.uk, + sara.boutamina@kcl.ac.uk, + mark.ormesher@kcl.ac.uk, + clarence.ji@kcl.ac.uk, + andrei.nae_-_stroie@kcl.ac.uk, + alexander.hanbury-Botherway@kcl.ac.uk, + rosen.dangov@kcl.ac.uk, + diana.ghitun@kcl.ac.uk, + andrei.juganaru@kcl.ac.uk, + ainur.makhmet@kcl.ac.uk \ No newline at end of file diff -r 48d2cbe8ee5e -r 70306f6c65b1 progs/collatz_sol2.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/progs/collatz_sol2.scala Tue Nov 15 23:04:52 2016 +0000 @@ -0,0 +1,55 @@ +// Part 1 about the 3n+1 conceture +//================================= + +//(1) Complete the collatz function below. It should +// recursively calculate the number of steps needed +// until the collatz series reaches the number 1. +// If needed you can use an auxilary function that +// performs the recursion. The function should expect +// arguments in the range of 1 to 1 Million. + +def collatz(n: Long): List[Long] = + if (n == 1) List(1) else + if (n % 2 == 0) (n::collatz(n / 2)) else + (n::collatz(3 * n + 1)) + + +// an alternative that calculates the steps directly +def collatz1(n: Long): Int = + if (n == 1) 1 else + if (n % 2 == 0) (1 + collatz1(n / 2)) else + (1 + collatz1(3 * n + 1)) + +import scala.annotation.tailrec + +@tailrec +def collatz2(n: Long, acc: Long): Long = + if (n == 1) acc else + if (n % 2 == 0) collatz2(n / 2, acc + 1) else + collatz2(3 * n + 1, acc + 1) + + +//(2) Complete the collatz bound function below. It should +// calculuate how many steps are needed for each number +// from 1 upto a bound and return the maximum number of +// steps and the corresponding number that needs that many +// steps. You should expect bounds in the range of 1 +// upto 1 million. + +def collatz_max(bnd: Long): (Long, Long) = { + (1L to bnd).view.map((i) => (collatz2(i, 1), i)).maxBy(_._1) +} + + +// some testing harness +//val bnds = List(10, 100, 1000, 10000, 100000, 1000000) +val bnds = List(10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000) + +for (bnd <- bnds) { + val (steps, max) = collatz_max(bnd) + println(s"In the range of 1 - ${bnd} the number ${max} needs the maximum steps of ${steps}") +} + + +//val all = for (i <- (1 to 100000).toList) yield collatz1(i) +//println(all.sorted.reverse.take(10))