-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSonar.js
56 lines (45 loc) · 1.48 KB
/
Sonar.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
var fs = require("fs");
var content = fs
.readFileSync("sonar-input.txt", "utf-8", (err) => {
if (err) return err;
})
.split("\n")
.map(Number);
let example = [199, 200, 208, 210, 200, 207, 240, 269, 260, 263];
// part 1
const compareDepthMeasurement = (allDepths) => {
let countAllLargerMeasurements = 0;
allDepths.map((measurment, i) => {
if (measurment > allDepths[i - 1]) {
countAllLargerMeasurements++;
}
});
console.log(
`There are ${countAllLargerMeasurements} measurements larger than the previous one`
);
return countAllLargerMeasurements;
};
compareDepthMeasurement(content);
// // part 2
const compareSumOfSlidingWindow = (allDepths) => {
let sumOfSlidingWindow = 0;
let slidingDepthsArray = [];
// push sum of measurement to slidingDepthArray as long as there is a three-measurement sliding window ->
// stop when there aren't enough measurements left to create a new three-measurement sum.
allDepths.map((measurement, i) => {
if (allDepths[i + 1] && allDepths[i + 2]) {
slidingDepthsArray.push(
measurement + allDepths[i + 1] + allDepths[i + 2]
);
}
// add one to sumOfSlidingWindow (counter) when sum of measurement is more than the previous one
if (slidingDepthsArray[i] > slidingDepthsArray[i - 1]) {
sumOfSlidingWindow++;
}
return slidingDepthsArray;
});
console.log(
`There are ${sumOfSlidingWindow} sums larger than the previous one`
);
};
compareSumOfSlidingWindow(content);