Skip to content

Instantly share code, notes, and snippets.

@ntrf
Last active September 22, 2023 23:33
Show Gist options
  • Save ntrf/fbe51edb1837fb8190b5b79ac11949f7 to your computer and use it in GitHub Desktop.
Save ntrf/fbe51edb1837fb8190b5b79ac11949f7 to your computer and use it in GitHub Desktop.
IdontNeedForLoops
// Don't you ever write code like this.
// -- Ntrf
import 'dart:math';
int waterTrapped(List<int> heights) {
int maxFwd = 0;
int maxRev = 0;
int res = heights.fold(0, (a, x) => a + (maxFwd = max(maxFwd, x)));
res += heights.reversed.fold(0, (a, x) => a + (maxRev = max(maxRev, x)));
return heights.fold(res, (a, x) => (a - x - maxFwd));
}
void run(List<int> list, int exp) =>
print("$list => ${waterTrapped(list)} ($exp expected)");
void main() {
run([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1], 6);
run([4, 2, 0, 3, 2, 5], 9);
run([],0);
run([0,0,0,0,0],0);
run([0,0,1,0,0],0);
run([1,0,0,0,1],3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment