0

I need to write a recursive function that would return a corresponding integer from the given list. For example, list1 = List(2,3,1,7,5) fromList(list1) would return 57132 This is what I have.

def fromList(list1: List[Int]): Int = { val num1 = list1.head val num2 = fromList(list1.tail) if (list1.isEmpty) num1 else num1 + num2 } 

I'm able to solve this if I use power operation but this operation is limited.

3 Answers 3

3

Something like this?

def fromList(list1: List[Int]): Int = list1.reverse.fold(0)(10 * _ + _) fromList(List(2,3,6)) //res0: Int = 632 

Can also be done with foldRight().

def fromList(list1: List[Int]): Int = list1.foldRight(0)(_ + _ * 10) 

If recursion is required...

@annotation.tailrec def fromList(list1: List[Int], acc:Int = 0): Int = if (list1.isEmpty) acc else fromList(list1.init, 10*acc + list1.last) fromList(List(2,3,6,1)) //res0: Int = 1632 

Or the slightly more verbose but likely more efficient...

def fromList(list1: List[Int]): Int = { @annotation.tailrec def loop(lst: List[Int], acc:Int = 0):Int = lst match { case hd::tl => loop(tl, 10*acc + hd) case _ => acc } loop(list1.reverse, 0) } fromList(List(7,3,6,4)) //res0: Int = 4637 

There are 2 major problems with your original design.

1st - Both list1.head and list1.tail are impossible if list1.isEmpty. So you need to test for that before decomposing the List.

2nd - You need to adjust the intermediate results before adding the current digit.

//recursive but not tail-recursive def fromList(list1: List[Int]): Int = if (list1.isEmpty) 0 else 10 * fromList(list1.tail) + list1.head 
Sign up to request clarification or add additional context in comments.

1 Comment

I really liked your solution but it has to be recursive
0

@jwvh solution is recursive(tail) if you might want a non tail recursive though with a good chance of a stack overflow for large values then

def solution (list : List[Int]): Int = { def recursive(list1: List[Int]): Int= { list1 match { case head :: tail => head * scala.math.pow(10, list1.length-1).toInt + recursive(tail) case Nil => 0 } } recursive(list.reverse) } 

1 Comment

Not only does this use a lot of stack, but it is O(n^2) rather than O(n) and uses pow rather than *. Why not recurse(tail)*10 + head?!
0

Not recursive, but does the job :)

list1.reverse.mkString("").toInt 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.