Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a sequence of Fibonacci number in Scala [duplicate]

Tags:

    def fibSeq(n: Int): List[Int] = {     var ret = scala.collection.mutable.ListBuffer[Int](1, 2)     while (ret(ret.length - 1) < n) {       val temp = ret(ret.length - 1) + ret(ret.length - 2)       if (temp >= n) {         return ret.toList       }       ret += temp     }     ret.toList   }  

So the above is my code to generate a Fibonacci sequence using Scala to a value n. I am wondering if there is a more elegant way to do this in Scala?

like image 899
nobody Avatar asked Mar 25 '12 22:03

nobody


People also ask

How do you write Fibonacci series in Scala?

Fibonacci numbers in Scala object Fibonacci { def fibonacci(n: Int): Int = if (n < 3) 1 else fibonacci(n - 1) + fibonacci(n - 2) def main(args: Array[String]) { for {i <- List. range(1, 17)} yield { print(fibonacci(i) + ", ") } println("...") } }

Does the Fibonacci sequence repeat?

The Fibonacci sequence has a pattern that repeats every 24 numbers. Numeric reduction is a technique used in analysis of numbers in which all the digits of a number are added together until only one digit remains. As an example, the numeric reduction of 256 is 4 because 2+5+6=13 and 1+3=4.


2 Answers

This is a bit more elegant:

val fibs: Stream[Int] = 0 #:: fibs.scanLeft(1)(_ + _) 

With Streams you "take" a number of values, which you can then turn into a List:

scala> fibs take 10 toList res42: List[Int] = List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34) 

Update: I've written a blog post which goes more detail regarding how this solution works, and why you end up with a Fibonacci sequence!

like image 86
Luigi Plinge Avatar answered Oct 27 '22 19:10

Luigi Plinge


There are many ways to define the Fibonacci sequence, but my favorite is this one:

val fibs:Stream[Int] = 0 #:: 1 #:: (fibs zip fibs.tail).map{ t => t._1 + t._2 } 

This creates a stream that is evaluated lazily when you want a specific Fibonacci number.

EDIT: First, as Luigi Plinge pointed out, the "lazy" at the beginning was unnecessary. Second, go look at his answer, he pretty much did the same thing only more elegantly.

like image 27
Tal Pressman Avatar answered Oct 27 '22 19:10

Tal Pressman