Last active
August 29, 2015 14:19
-
-
Save schmohlio/37563d79db5d05199128 to your computer and use it in GitHub Desktop.
finding sum of two largest values in list (unordered).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
note that this doesn't incorporate case when list is length 1 properly. could probably start with 0s