What is wrong with this Scala recursive code? - scala

I have recently started learning Scala and trying to implement a recursive function in it. My goal for this exercise is to return the nth number in the fibonacci series.
def fib(n: Int ): Int = {
def go(n:Int, prev:Int, curr: Int, res:Int): Int =
if (n == 0 ) res
else go(n-1, curr, prev+curr, prev+curr)
go (n, 0, 1, 0 )
}
def main(args: Array[String]): Int =
println(fib(7))
There are no compilation errors, however the result comes as open and close parenthesis.
Result--> ()
Any advise.

Finally, I got this.
Here is how I have done.
def fib(n: Int ) : Int = {
def go(n: Int, prev: Int, curr: Int, res: Int): Int =
if (n == 0 ) res
else go(n-1, curr, prev+curr, prev+curr)
go (n-2, 0, 1, 0 )
}
def main(args: Array[String]): Unit =
println(fib(10))

Related

Recursive to Tail-recursive in scala

I have the following code
object TailRec
{
def func1(n:Int) : Int =
{
if (n < 10)
func2(n)
else
func1(n/10) + func2(n % 10)
}
def func2(n: Int) : Int =
{
#tailrec def _func2(n: Int, result: Int): Int =
{
if (n <= 1)
result
else
_func2(n-1,n*result)
}
_func2(n,1)
}
def test(n: Int) : Boolean =
{
if (n > 2)
n == func1(n)
else
false
}
}
I managed to rewrite func2 but I am not quite sure how to convert the bool function. I thought about match and case but I still need to call func1 to get the result for comparison. The other problem is how to break up the double function call in func1 itself. Any hints?
You have already converted func2 into tail-recursive form.
Similarly, using an additional accumulator, you can convert func1 into a tail-recursive form (I have modified the interface of func1, but you could also create another inner helper function). Since test isn't recursive, nothing has to be done here.
import scala.annotation.tailrec
object TailRec {
#tailrec def func1(n:Int, acc: Int): Int = {
if (n < 10) func2(n)
else func1(n / 10, acc + func2(n % 10))
}
def func2(n: Int): Int = {
#tailrec def _func2(n: Int, result: Int): Int = {
if (n <= 1) result
else _func2(n-1,n*result)
}
_func2(n,1)
}
def test(n: Int): Boolean = (n > 2) && (n == func1(n, 0))
}

calling println on a user defined function formatResult 3 times from main, but execution order is different

I am very new to Scala. I tried calling formatResult inside println 3 times from main passing abs, fact, fib in that order.
But the output shows a different execution order - fact, fib, abs
/* MyModule.scala */
object MyModule {
def abs(n: Int): Int =
if(n < 0)
-n
else
n
def fact(n: Int): Int = {
def go(n: Int, acc: Int): Int = {
if(n <= 1)
acc
else
go(n - 1, n * acc)
}
go(n, 1)
}
def fib(n: Int): Int = {
def loop(n: Int, prev: Int, curr: Int): Int = {
if(n == 0)
prev
else
loop(n - 1, curr, prev + curr)
}
loop(n, 0, 1)
}
private def formatResult(fName: String, placeholder: String, n: Int, f: Int => Int) = {
val msg = "The %s %s %d is %d"
msg.format(fName, placeholder, n, f(n))
}
def main(args: Array[String]): Unit =
println(formatResult("absolute value", "of", -10, abs))
println(formatResult("factorial", "of", 5, fact))
println(formatResult("fibonacci number", "at index", 8, fib))
}
/* output */
The factorial of 5 is 120
The fibonacci number at index 8 is 21
The absolute value of -10 is 10
Could someone please explain this to me?
Your main method code is not surround by braces. So your main method becomes just the following:
def main(args: Array[String]): Unit =
println(formatResult("absolute value", "of", -10, abs))
The other two print lines are executed as the object is setup. So they run before the main method is called. The following will work correctly:
def main(args: Array[String]): Unit = {
println(formatResult("absolute value", "of", -10, abs))
println(formatResult("factorial", "of", 5, fact))
println(formatResult("fibonacci number", "at index", 8, fib))
}

Scala data structure and complexity O(1)

Today I had an interview about Scala and request was:
Implement a data structure with fixed size N , with these functionalities:
get(index)
set(index,value)
setall(value)
The complexity should be O(1)
example:
val ds = DS(100)
ds.set(4,5)
ds.get(4) //would return 5
ds.set(1,4)
ds.setall(10)
ds.get(4) //would return 10
ds.get(7) //would return 10
ds.set(1,7)
ds.get(1) //would return 7
Please find code that I have sent below.
My question would be Is this right solution and if there is a better way of doing it ?
import scala.collection.mutable.HashMap
trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int)
def setall(value: Int)
}
class DS(N: Int) extends Operations {
var myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(0)
def get(index: Int) = myMutableHashMap(index)
def set(index: Int, value: Int) = {
if (index <= N) myMutableHashMap += (index -> value)
}
def setall(value: Int) = {
myMutableHashMap = new HashMap[Int, Int]().withDefaultValue(value)
}
}
object Task {
def main(args: Array[String]): Unit = {
val ds = new DS(100)
ds.set(4, 5)
ds.get(4)
println(ds.get(4)) // -> 5
ds.setall(10)
println(ds.get(4)) //-> 10
println(ds.get(7)) //-> 10
ds.set(1, 7)
println(ds.get(1)) //-> 7
}
}
I am not sure if it is better, but I think HashMap might be a bit of an overkill.
The following solution might have a smaller footprint and takes less code.
Although, I would probably rather implement something more generic, it should fulfill the requirements you mentioned.
trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int): Unit
def setall(fill: Int): Unit
}
class DS(size: Int) extends Operations {
val underlying: Array[Int] = new Array(size)
def get(index: Int): Int = underlying(index)
def set(index: Int, value: Int): Unit = underlying(index) = value
def setall(fill: Int): Unit = (0 until size).foreach(underlying(_) = fill)
}
Alternative, which just might give us a better 'setall' complexity but at a cost ...
trait Operations {
def get(index: Int): Int
def set(index: Int, value: Int): Unit
def setall(fill: Int): Unit
}
class DS(size: Int) extends Operations {
var underlying: Array[Integer] = new Array(size)
var default: Integer = new Integer(0)
def get(index: Int): Int = {
val result = underlying(index)
if (result == null) default else result
}
def set(index: Int, value: Int): Unit = underlying(index) = value
def setall(fill: Int): Unit = {
default = fill
underlying = new Array(size)
}
}

Scala : statements are not executed in order

I am learning scala I tried following program
package com.avdongre
object MyModule {
def abs(n: Int): Int =
if (n < 0) -n
else n
private def formatAbs(x: Int) = {
val msg = "The absolute value of %d is %d"
msg.format(x, abs(x))
}
def factorial(n: Int): Int = {
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n - 1, n * acc)
go(n, 1)
}
def main(args: Array[String]): Unit =
println(formatAbs(-42))
println(factorial(5))
}
I get following output
120
The absolute value of -42 is 42
Why factorial is getting called first ?
You need curly braces around your body of main:
def main(args: Array[String]): Unit = {
println(formatAbs(-42))
println(factorial(5))
}
What is happening is you have this (with corrected indentation for clarity):
def main(args: Array[String]): Unit =
println(formatAbs(-42))
println(factorial(5))
Hence when the object MyModule gets initialized, the last statement of the body is println(factorial(5)) which occurs before your main method.

StackOverflowError for coin change in Scala?

I'm writing a recursive function for the Coin (change) problem in Scala.
My implementation breaks with StackOverflowError and I can't figure out why it happens.
Exception in thread "main" java.lang.StackOverflowError
at scala.collection.immutable.$colon$colon.tail(List.scala:358)
at scala.collection.immutable.$colon$colon.tail(List.scala:356)
at recfun.Main$.recurs$1(Main.scala:58) // repeat this line over and over
this is my call:
println(countChange(20, List(1,5,10)))
this is my definition:
def countChange(money: Int, coins: List[Int]): Int = {
def recurs(money: Int, coins: List[Int], combos: Int): Int =
{
if (coins.isEmpty)
combos
else if (money==0)
combos + 1
else
recurs(money,coins.tail,combos+1) + recurs(money-coins.head,coins,combos+1)
}
recurs(money, coins, 0)
}
Edit: I just added the else if statement in the mix:
else if(money<0)
combos
it got rid of the error but my output is 1500 something :( what is wrong with my logic?
The first solution in the accepted answer has a redundant last parameter as noted by Paaro so I wanted to get rid of it. The second solution uses map which I wanted to avoid since it wasn't covered yet in the Week 1 or the Scala course I assume you're taking. Also, the second solution, as rightly noted by the author, would be way slower, unless it uses some memoization. Finally, Paaro's solution seems to have an unnecessary nested function.
So here's what I ended up with:
def countChange(money: Int, coins: List[Int]): Int =
if (money < 0)
0
else if (coins.isEmpty)
if (money == 0) 1 else 0
else
countChange(money, coins.tail) + countChange(money - coins.head, coins)
There is no need for braces here, as you can see.
I wonder if it could be further simplified.
Here is the correct solution based on your codes:
def countChange(money: Int, coins: List[Int]): Int = {
def recurs(m: Int, cs: List[Int], cnt: Int): Int =
if(m < 0) cnt //Not a change, keep cnt
else if(cs.isEmpty) {
if(m == 0) cnt + 1 else cnt // plus cnt if find a change
}
else recurs(m, cs.tail, cnt) + recurs(m-cs.head, cs, cnt)
recurs(money, coins, 0)
}
Anyway, there is a short solution(But not efficient, you can cache the middle result to make it efficient.)
def countChange(m: Int, cs: List[Int]): Int = cs match {
case Nil => if(m == 0) 1 else 0
case c::rs => (0 to m/c) map (k => countChange(m-k*c,rs)) sum
}
One can omit the cnt parameter, which is, in fact, never accumulated. The recurs function always returns either 0 or 1, so the optimized algorithm would be:
def countChange(money: Int, coins: List[Int]): Int = {
def recurs(m: Int, cs: List[Int]): Int =
if(m < 0) 0 //Not a change, return 0
else if(cs.isEmpty) {
if(m == 0) 1 else 0 // 1 if change found, otherwise 0
}
else recurs(m, cs.tail) + recurs(m-cs.head, cs)
if(money>0) recurs(money, coins) else 0
}
The #Eastsun solution is good but it fails when money=0 due to it returns 1 instead of 0, but you can fix it easily:
def countChange(money: Int, coins: List[Int]): Int = {
def recurs(m: Int, cs: List[Int], cnt: Int): Int =
if(m < 0) cnt //Not a change, keep cnt
else if(cs.isEmpty) {
if(m == 0) cnt + 1 else cnt // plus cnt if find a change
}
else recurs(m, cs.tail, cnt) + recurs(m-cs.head, cs, cnt)
if(money>0) recurs(money, coins, 0) else 0
}
here is a DP approach to reduce a lot of re-calculation in recursive approach
object DP {
implicit val possibleCoins = List(1, 5, 10, 25, 100)
import collection.mutable.Map
def countChange(amount: Int)(implicit possibleCoins: List[Int]) = {
val min = Map((1 to amount).map (_->Int.MaxValue): _*)
min(0) = 0
for {
i <- 1 to amount
coin <- possibleCoins
if coin <= i && min(i - coin) + 1 < min(i)
} min(i) = min(i-coin) + 1
min(amount)
}
def main(args: Array[String]) = println(countChange(97))
}
see DP from novice to advanced for algorithm
Idea from https://github.com/pathikrit/scalgos/blob/9e99f73b4241f42cc40a1fd890e72dbeda2df54f/src/main/scala/com/github/pathikrit/scalgos/DynamicProgramming.scala#L44
case class Memo[K,I,O](f: I => O)(implicit i2k:I=>K ) extends (I => O) {
import scala.collection.mutable.{Map => Dict}
val cache = Dict.empty[K, O]
override def apply(x: I) = cache getOrElseUpdate (x, f(x))
}
def coinchange(s: List[Int], t: Int) = {
type DP = Memo[ (Int, Int), (List[Int], Int),Seq[Seq[Int]]]
implicit def encode(key: (List[Int], Int)):(Int,Int) = (key._1.length, key._2)
lazy val f: DP = Memo {
case (Nil, 0) => Seq(Nil)
case (Nil, _) => Nil
case (_, x) if x< 0 => Nil
case (a :: as, x) => f(a::as, x - a).map(_ :+ a) ++ f(as, x)
}
f(s, t)
}