List of Integers to Int (Add for odd, multiply for even)

Sudarshan Kasar
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))
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudarshan Kasar
Sudarshan Kasar

No responses yet

Write a response