progs/lecture2.scala
changeset 56 6fa91be92d0c
parent 55 6610c1dfa8a9
child 57 9b88f9e04344
equal deleted inserted replaced
55:6610c1dfa8a9 56:6fa91be92d0c
   276 def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
   276 def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
   277 
   277 
   278 sum_squares(lst)
   278 sum_squares(lst)
   279 sum_cubes(lst)
   279 sum_cubes(lst)
   280 
   280 
       
   281 
       
   282 
       
   283 // Avoid being mutable
       
   284 //=====================
       
   285 
       
   286 // a student showed me...
       
   287 import scala.collection.mutable.ListBuffer
       
   288 
       
   289 def collatz_max(bnd: Long): (Long, Long) = {
       
   290   val colNos = ListBuffer[(Long, Long)]()
       
   291   for (i <- (1L to bnd).toList) colNos += ((collatz(i), i))
       
   292   colNos.max
       
   293 }
       
   294 
       
   295 def collatz_max(bnd: Long): (Long, Long) = {
       
   296   (1L to bnd).map((i) => (collatz(i), i)).maxBy(_._1)
       
   297 }
       
   298 
       
   299 //views -> lazy collection
       
   300 def collatz_max(bnd: Long): (Long, Long) = {
       
   301   (1L to bnd).view.map((i) => (collatz(i), i)).maxBy(_._1)
       
   302 }
       
   303 
       
   304 // raises a GC exception
       
   305 (1 to 1000000000).filter(_ % 2 == 0).take(10).toList
       
   306 // ==> java.lang.OutOfMemoryError: GC overhead limit exceeded
       
   307 
       
   308 (1 to 1000000000).view.filter(_ % 2 == 0).take(10).toList
   281 
   309 
   282 // Sudoku
   310 // Sudoku
   283 //========
   311 //========
   284 
   312 
   285 val game0 = """.14.6.3..
   313 val game0 = """.14.6.3..