ArmandNM / lambda-workshop-2018

Scala implementation of algorithm interview questions done during the Lambda Workshop organized by ROSEdu.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[refactoring] TwoSum.scala

opened this issue · comments

case class Accumulator(values: Map[Int,Int], pair: List[Int])

val targetSum = 6
val inputValues = List(3,2,4)
val initialAcc = Accumulator(Map.empty[Int,Int], List.empty[Int])

def foldLeftFn(targetSum: Int)(acc: Accumulator, crtTuple: (Int,Int)): Accumulator = {
  val (crtValue, crtIndex) = crtTuple
  val diff = targetSum - crtValue
  val nextPair = if (acc.values.contains(diff)) { acc.values.get(diff).get :: crtIndex :: acc.pair } else acc.pair
  Accumulator(acc.values + (crtValue -> crtIndex), nextPair)
}

val answer = {
  inputValues
    .zipWithIndex
    .foldLeft(initialAcc)(foldLeftFn(targetSum))
    .pair
}