-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22-Waterfall-problem.js
58 lines (48 loc) · 1.45 KB
/
22-Waterfall-problem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
function waterfallStreams(array, source) {
// Write your code here.
let rowAbove = [...array[0]];
rowAbove[source] = -1;
for (let index = 1; index < array.length; index++) {
let currentRow = [...array[index]];
for (let idx = 0; idx < rowAbove.length; idx++) {
let aboveValue = rowAbove[idx];
const hasWater = aboveValue < 0;
const currentlyFacingBlock = currentRow[idx] === 1;
if (!hasWater) {
continue;
}
if (!currentlyFacingBlock) {
currentRow[idx] += aboveValue; // water flowed down
continue;
}
const splitWater = aboveValue / 2;
let rightIdx = idx + 1;
while (rightIdx < rowAbove.length) {
if (rowAbove[rightIdx] === 1) {
break;
}
if (currentRow[rightIdx] !== 1) {
currentRow[rightIdx] += splitWater; // water flowed down
break;
}
rightIdx++;
}
let leftIdx = idx - 1;
while (leftIdx >= 0) {
if (rowAbove[leftIdx] === 1) {
break;
}
if (currentRow[leftIdx] !== 1) {
currentRow[leftIdx] += splitWater; // water flowed down
break;
}
leftIdx--;
}
}
rowAbove = currentRow;
}
const finalPercentRow = rowAbove.map((item) => item * -100);
return finalPercentRow;
}
// Do not edit the line below.
exports.waterfallStreams = waterfallStreams;