Commits

Ignasi Marimon-Clos committed b5c2eb6

Improve solution to problem number 2 by only generating odd values

  • Participants
  • Parent commits f7f7fa3

Comments (0)

Files changed (2)

File src/main/scala/com/marimon/xmpp/Problem2.scala

 
 class Problem2 {
 
-  var status: Int = 1
+  var status: Int = 0
 
   var previous: Int = 0
 
   def iterator(): Iterator[Int] = {
     return Iterator.continually[Int]({
-      val result: Int = status + previous;
+      val result: Int = if (status == 0 && previous == 0) 1 else status + previous;
       previous = status;
       status = result;
-      if (previous == 1) previous else result
+      result
     });
   }
 
-  def solve(): Int = {
-    iterator().takeWhile(_ < 4000000).foldLeft(0)((r, c) => if (c % 2 == 0) r else r + c)
-  }
+  var itr = iterator()
 
-}
+  var count: Int = 0;
 
-object Problem2 {
+  private def skipIterator(): Iterator[Int] = {
+    return Iterator.continually[Int]({
+      if (count % 3 == 2) {
+        itr.next
+        count += 1
+      }
+      count += 1;
+      itr.next
+    });
+  }
 
-  def fib(input: Int): Int = {
-    input match {
-      case 2 => 1
-      case 1 => 1
-      case _ => fib(input - 1) + fib(input - 2)
-    }
+  def solve(): Int = {
+    skipIterator().takeWhile(_ < 4000000).foldLeft(0)((r, c) => r + c)
   }
 
-}
+}
+

File src/test/scala/com/marimon/xmpp/Problem2Test.scala

   //By considering the terms in the Fibonacci sequence whose values do not 
   //exceed four million, find the sum of the even-valued terms.
 
-  "The Problem2" should "compute Fibonacci of 1" in {
-    Problem2.fib(1) should be(1)
+  "The Problem2" should "provide 1st Fibonacci value as an interator" in {
+    val itr: Iterator[Int] = new Problem2().iterator();
+    itr.next() should be(1)
   }
-  it should "compute Fibonacci of 2" in {
-    Problem2.fib(2) should be(1)
+
+  it should "provide 2nd Fibonacci value as an interator" in {
+    val itr: Iterator[Int] = new Problem2().iterator();
+    itr.next()
+    itr.next() should be(1)
+  }
+  it should "provide 3rd Fibonacci value as an interator" in {
+    val itr: Iterator[Int] = new Problem2().iterator();
+    itr.next()
+    itr.next()
+    itr.next() should be(2)
   }
-  it should "compute Fibonacci of 6" in {
-    Problem2.fib(6) should be(8)
+  it should "provide 6th Fibonacci value as an interator" in {
+    val itr: Iterator[Int] = new Problem2().iterator();
+    itr.next()
+    itr.next()
+    itr.next()
+    itr.next()
+    itr.next()
+    itr.next() should be(8)
   }
-  it should "solve the problem" in {
-    // Problem2.solve(10) should be(1000)
+
+  it should "be solved" in {
     new Problem2().solve should be(4613732)
   }