Skip to content

Commit d114b2d

Browse files
feat(2020-day-09): find the first invalid value in a data set
1 parent e65e9c5 commit d114b2d

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

2020/day-09/xmasEncryption.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,25 @@
1+
const findInvalid = (data, preambleSize) => {
2+
let match = true
3+
let counter = preambleSize
4+
5+
while (match === true && counter < data.length) {
6+
console.debug(`Looking for mismatch ${data[counter]} in:`)
7+
console.debug(data.slice(counter - preambleSize, counter))
8+
console.debug('-----------------------------------------')
9+
match = isValid(
10+
data[counter],
11+
data.slice(counter - preambleSize, counter)
12+
)
13+
if (!match) {
14+
console.debug(`${data[counter]} doesn't match.`)
15+
return data[counter]
16+
}
17+
counter++
18+
}
19+
20+
throw new Error('No invalid values found')
21+
}
22+
123
const isValid = (value, preamble) => {
224
let valid = false
325

@@ -16,5 +38,6 @@ const isValid = (value, preamble) => {
1638
}
1739

1840
module.exports = {
41+
findInvalid,
1942
isValid
2043
}

2020/day-09/xmasEncryption.test.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/* eslint-env mocha */
22
const { expect } = require('chai')
3-
const { isValid } = require('./xmasEncryption')
3+
const { isValid, findInvalid } = require('./xmasEncryption')
44

55
const range = (i) => { return i ? range(i - 1).concat(i) : [] }
66

@@ -25,5 +25,18 @@ describe('--- Day 9: Encoding Error ---', () => {
2525
expect(isValid(66, preamble), '65 is valid').to.equal(true)
2626
})
2727
})
28+
describe('findInvalid()', () => {
29+
it('searches a data set for the first invalid data based on the defined preamble size', () => {
30+
const data = [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576]
31+
const preambleSize = 5
32+
expect(
33+
findInvalid(data, preambleSize),
34+
`127 cannot be summed from the previous ${preambleSize} numbers`
35+
).to.equal(127)
36+
})
37+
it('throws an error if no invalid value is found', () => {
38+
expect(() => { findInvalid([1, 2, 3, 5, 8, 13], 2) }).to.throw('No invalid values found')
39+
})
40+
})
2841
})
2942
})

0 commit comments

Comments
 (0)