Created
April 28, 2015 10:48
How to search for an element in an array while passing state for the next iteration
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 numbers = readLine().split(" ").map(_.toInt) // an array of numbers | |
val leftSums = numbers.scan(0)(_ + _).init // calculate cumulative sums from left | |
// search from right to find the same sum from left | |
var sum = 0 | |
val result = numbers.zipWithIndex.reverse.find { case (number, index) => | |
if (sum == leftSums(index)) true | |
else { | |
sum = sum + number | |
false | |
} | |
} |
@metanet my answer for @korayal applies to you. And also this: https://twitter.com/fehmicans/status/593039964268552192
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@fehmicansaglam you can replace
scan
with afold*
/reduce
variant by passing a list of accumulated values at each step.