Skip to content

Commit 308ddca

Browse files
feat(2020-day-10): tally up the voltage differences across the set of adapters
1 parent 94cf63b commit 308ddca

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

2020/day-10/jolts.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
11
const countDifferences = (data) => {
2-
if (data.length > 15) {
3-
return [0, 22, 0, 10]
4-
}
5-
return [0, 7, 0, 5]
2+
const tallies = Array(4).fill(0)
3+
// Always account for the outlet
4+
data.push(0)
5+
// Always add the native adapter at the end
6+
tallies[3]++
7+
8+
// Iterate through the adapters
9+
data.sort((a, b) => a - b)
10+
.forEach((curr, idx) => {
11+
if (!data[idx + 1]) {
12+
// end of array, nothing to do
13+
return
14+
}
15+
const next = data[idx + 1]
16+
const delta = next - curr
17+
if (delta > 3) {
18+
// Problem with data. Gap in joltages greater than allowed
19+
throw new Error(`Joltage difference between ${curr} and ${next} is greater than allowed.`)
20+
}
21+
22+
console.debug(`Joltage difference between ${curr} and ${next} is ${delta}.`)
23+
tallies[delta]++
24+
})
25+
26+
return tallies
627
}
728

829
module.exports = {

2020/day-10/jolts.test.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ describe('--- Day 10: Adapter Array ---', () => {
1818
expect(result2[1]).to.equal(22)
1919
expect(result2[3]).to.equal(10)
2020
})
21+
it('throws an error if any joltage differences exceed 3', () => {
22+
expect(() => countDifferences([5, 40])).to.throw()
23+
})
2124
})
2225
})
2326
})

0 commit comments

Comments
 (0)