can't get second part done
This commit is contained in:
parent
f6cff3a1c4
commit
6c165f08c0
1 changed files with 40 additions and 0 deletions
|
@ -35,7 +35,47 @@ class DayTwo implements Solvable {
|
|||
|
||||
return this
|
||||
}
|
||||
|
||||
public part2(): DayTwo {
|
||||
const reports = this.input.trim().split("\n").map(line => line.split(' ').map(level => Number.parseInt(level)))
|
||||
const slidingWindow = (levels: number[]): boolean => {
|
||||
const gradients: ("ascending" | "descending" | "stagnating")[] = []
|
||||
const diffs: number[] = []
|
||||
let [i,j] = [0,1]
|
||||
while (j < levels.length) {
|
||||
// is unsafe if ascent / descend bigger than 3 or smaller than 1
|
||||
const diff = Math.abs(levels[i] - levels[j])
|
||||
diffs.push(diff)
|
||||
// calculate positive or negative gradient
|
||||
if (levels[i] < levels[j]) {
|
||||
gradients.push("ascending")
|
||||
} else if (levels[i] > levels[j]) {
|
||||
gradients.push("descending")
|
||||
} else {
|
||||
gradients.push("stagnating")
|
||||
}
|
||||
i++
|
||||
j++
|
||||
}
|
||||
|
||||
// amount of unsafe diffs
|
||||
const unsafeDiffs = diffs.filter((diff) => diff > 3 || diff < 1).length
|
||||
|
||||
// how many gradients are ascending / descending?
|
||||
const ascendingAmount = gradients.filter((gradient) => gradient === "ascending").length
|
||||
const descendingAmount = gradients.filter((gradient) => gradient === "descending").length
|
||||
|
||||
// accept one unsafe diff if all gradients either ascending or descending
|
||||
if (ascendingAmount === gradients.length || descendingAmount === gradients.length && unsafeDiffs === 1) return true
|
||||
|
||||
// allow for a single wrong gradient
|
||||
const ascendingExceptOne = ascendingAmount >= gradients.length - 1
|
||||
const descendingExceptOne = descendingAmount >= gradients.length - 1
|
||||
return ascendingExceptOne || descendingExceptOne
|
||||
}
|
||||
const result = reports.map(levels => slidingWindow(levels)).filter(level_safe => level_safe === true).length
|
||||
console.log(result)
|
||||
|
||||
return this
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue