Commits

Ignasi Marimon-Clos  committed f7f7fa3

Solve the problem number 2

  • Participants
  • Parent commits 96ffb12

Comments (0)

Files changed (2)

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

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

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

+package com.marimon.xmpp
+import org.scalatest.FlatSpec
+import org.scalatest.matchers.ShouldMatchers
+import org.junit.runner.RunWith
+import org.scalatest.junit.JUnitRunner
+import scala.collection.immutable.IndexedSeq
+
+@RunWith(classOf[JUnitRunner])
+class Problem2Test extends FlatSpec with ShouldMatchers {
+  //Each new term in the Fibonacci sequence is generated by adding the 
+  //previous two terms. By starting with 1 and 2, the first 10 terms will be:
+  //1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
+  // 
+  //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)
+  }
+  it should "compute Fibonacci of 2" in {
+    Problem2.fib(2) should be(1)
+  }
+  it should "compute Fibonacci of 6" in {
+    Problem2.fib(6) should be(8)
+  }
+  it should "solve the problem" in {
+    // Problem2.solve(10) should be(1000)
+    new Problem2().solve should be(4613732)
+  }
+
+}