Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Last active August 29, 2015 14:19
Show Gist options
  • Save schmohlio/37563d79db5d05199128 to your computer and use it in GitHub Desktop.
Save schmohlio/37563d79db5d05199128 to your computer and use it in GitHub Desktop.
finding sum of two largest values in list (unordered).
val sample = List(1,2,3,3,5,4,6,7,4)
// a good default if sample is always positive integers.
val START = (-1, -1)
// this is what I meant by default foldLeft (or scanLeft) value
val two_largest = test.foldLeft(START) { (acc: (Int, Int), n: Int) =>
val (smaller, larger) = acc
if (n > larger)
(larger, n)
else if (n > smaller)
(n, larger)
else
(smaller, larger)
}
// ANSWER:
two_largest._1 + two_largest._2
@schmohlio
Copy link
Author

note that this doesn't incorporate case when list is length 1 properly. could probably start with 0s

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