List of Integers to Int (Add for odd, multiply for even)
1 min readFeb 20, 2024
Problem statement —
* Read the elements a and b from the given stream or array
* Perform multiplication if the index is even. (a*b) for even
* For odd perform addition. (a+b) for odd
eg. Input (6,4,1,9,2) => output 38
Using scala, with foldleft, match case, and tail recusrion
package playground
import scala.annotation.tailrec
object Exercise extends App {
/**
* Read the elements a and b from the given stream or array
* Perform multiplication if the index is even. (a*b) for even
* For odd perform addition. (a+b) for odd
*
* eg Input (6,4,1,9,2) => output 38
* */
val arrayInt: Array[Int] = Array(6, 4, 1, 9, 2)
//using foldLeft
def logicImplementation(inputNumbers: Array[Int]): Int = {
//considering true = odd false = even
inputNumbers.foldLeft((1, false)) { (a, b) =>
/*val ret = a._2 match { // This is another way
case Some(x1) => if (x1) Tuple2(a._1 + b, Some(false)) else Tuple2(a._1 * b, Some(true))
case None => Tuple2(a._1 * b, Some(true))
}*/
println(s"($a, $b)")
if (a._2) Tuple2(a._1 + b, false) else Tuple2(a._1 * b, true)
//ret
}._1
}
println(logicImplementation(arrayInt))
//Using tail recursion
@tailrec
def logicWithTailRec(inputNumbers: Array[Int], isEven: Boolean = false): Int = {
val operation: (Int, Int, Boolean) => Tuple2[Int, Boolean] =
(a, b , condition) => if (condition) Tuple2(a * b, false) else Tuple2(a + b, true)
val res = operation(inputNumbers(0), inputNumbers(1), isEven)
if (inputNumbers.size == 2) {
res._1
} else {
logicWithTailRec(res._1 +: inputNumbers.slice(2, inputNumbers.size), res._2)
}
}
println(logicWithTailRec(arrayInt))
}