fork download
  1. object Main extends App {
  2.  
  3. val list:List[Int] = List(1, 4, 20, 3, 10, 5)
  4. val sum = 33
  5.  
  6. //Solution 1 :
  7. val sumList = list.foldLeft(List(0), 0)((l, r) => (l._1 :+ (l._2+r), l._2 + r))._1.drop(1)
  8. //Brute force approach
  9. sumList.zipWithIndex.combinations(2).toList.collectFirst({
  10. case i if i(1)._1 - i(0)._1 == sum => i
  11. }) match {
  12. case Some(List(x, y)) => println("elements which form the given sum are => "+ list.drop(x._2+1).take(y._2-x._2))
  13. case _ => println("couldn't find elements which satisfy the given condition")
  14. }
  15.  
  16. }
Success #stdin #stdout 0.43s 322240KB
stdin
Standard input is empty
stdout
elements which form the given sum are => List(20, 3, 10)