Given an array of integers, update the index with multiplication of previous and next integers,
Input: 2 , 3, 4, 5, 6
Output: 2*3, 2*4, 3*5, 4*6, 5*6
Following is a scala implementation for the same. Kindly review.
import scala.util.Random
object NeighborMultiplication extends App {
val numbers = List.fill(10)(Random.nextInt(10))
println(numbers mkString ",")
def multiplication(l: List[Int], carryOver: Int = 1, useCarryOver: Boolean = false ): List[Int] = l match {
case Nil => List()
case x::Nil => List(carryOver * x)
case x::y::Nil => List(carryOver * x * y, y * x)
case x::y::z::Nil => List(carryOver * x * y, x * z, y * z)
case x::y::z::tail =>
if (useCarryOver) List(carryOver * y, x * z, y * tail.head) ++ multiplication(tail, z, true)
else List(x * y, x * z, y * tail.head) ++ multiplication(tail, z, true)
}
println(multiplication(numbers).mkString(","))
}