Skip to content

Instantly share code, notes, and snippets.

@joshuakfarrar
Last active January 30, 2019 22:10
Show Gist options
  • Save joshuakfarrar/9d2e316da5cce3014de04828bd404283 to your computer and use it in GitHub Desktop.
Save joshuakfarrar/9d2e316da5cce3014de04828bd404283 to your computer and use it in GitHub Desktop.
// given a List[Int], e.g. List(1, 50, 250, 250, 50, 6), find all the pairs of numbers which sum to 500
def pairsOfSumOfN(ns: List[Int], n: Int): List[(Int, Int)] =
ns.zipWithIndex.map(pair => ns.zipWithIndex.filter(_._2 != pair._2).map(_._1).zipWithIndex.map(second => (pair._1, second._1))).flatMap(a => a.filter(b => n == (b._1 + b._2)))
pairsOfSumOfN(List(1, 50, 250, 250, 50, 6), 500) // returns List((250, 250), (250, 250))! (can we dedupe this list by using indexes? you bet!)
@joshuakfarrar
Copy link
Author

Easy to produce in ~5 minutes with Ammonite. Standing at a whiteboard? Please no.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment