Friday, February 8, 2013

Project Euler - Problem 001


I haven't been working with scala too much lately because I really haven't found any projects that I feel I can accomplish yet with a new language. Though, I heard about project euler the other day and noticed that each problem is a simple math calculation to solve. I thought this would be the perfect opportunity to start learning a new language and take advantage of some of scala's functional programming aspects.

So I took on problem1 during lunch today and found it to be not so terrible:

 package scala  
 import java.util.concurrent.TimeUnit  
 /**  
  * Problem 001 in scala.  
  */  
 object Problem001 extends App {  
  val timeUnit = TimeUnit.MILLISECONDS  
  val startTime = System.currentTimeMillis()  
  // Create a list of 1000 numbers  
  val buffer = for (i <- List.range(0, 1000) if (i % 3 == 0) || (i % 5 == 0)) yield i  
  val sum = buffer.toList.foldLeft(0)(_ + _)  
  println(sum)  
  val endTime = System.currentTimeMillis()  
  println("Time elapsed in seconds: " + timeUnit.toSeconds(endTime - startTime))  
 }  

I definitely see this as a way to keep learning a new language and to keep my mind sharp with these kinds of problems. Hopefully problem 2 goes as well as the first one did.

1 comment:

  1. Project Euler is great, but I would also recommend Rosalind (http://rosalind.info/problems/list-view/) which has a bioinformatics twist to it. It is intended for Python, but you can just as easily solve the problems in any language.

    ReplyDelete