Skip to content

Commit 6bb92a6

Browse files
feat(2020-day-09): find a weakness range in the encrypted data stream
1 parent e85e46e commit 6bb92a6

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

2020/day-09/xmasEncryption.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,26 @@
1+
const arrSum = arr => arr.reduce((a, b) => a + b, 0)
2+
3+
const findWeaknessRange = (data, target) => {
4+
let counter = 0
5+
while (counter < data.length) {
6+
const range = []
7+
let rangeCounter = counter
8+
// Tally up the next set of values trying to hit target
9+
while (arrSum(range) < target && rangeCounter < data.length) {
10+
range.push(data[rangeCounter])
11+
12+
if (arrSum(range) === target) {
13+
console.debug(`Found range totally ${target}`, range)
14+
return range
15+
}
16+
rangeCounter++
17+
}
18+
counter++
19+
}
20+
21+
throw new Error('No range found matching target')
22+
}
23+
124
const findInvalid = (data, preambleSize) => {
225
let match = true
326
let counter = preambleSize
@@ -23,6 +46,9 @@ const findInvalid = (data, preambleSize) => {
2346
const isValid = (value, preamble) => {
2447
let valid = false
2548

49+
// TODO: Speed this up by breaking out of while() loops instead
50+
// of forEach
51+
//
2652
// Search for a combination of 2 entries that add up to `value`
2753
preamble.forEach((outer) => {
2854
preamble.forEach((inner) => {
@@ -39,5 +65,6 @@ const isValid = (value, preamble) => {
3965

4066
module.exports = {
4167
findInvalid,
68+
findWeaknessRange,
4269
isValid
4370
}

2020/day-09/xmasEncryption.test.js

Lines changed: 12 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, findInvalid } = require('./xmasEncryption')
3+
const { isValid, findInvalid, findWeaknessRange } = require('./xmasEncryption')
44

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

@@ -38,5 +38,16 @@ describe('--- Day 9: Encoding Error ---', () => {
3838
expect(() => { findInvalid([1, 2, 3, 5, 8, 13], 2) }).to.throw('No invalid values found')
3939
})
4040
})
41+
describe('findWeaknessRange()', () => {
42+
it('locates a range of congtiguous values that sum up to the provided input', () => {
43+
const data = [35, 20, 15, 25, 47, 40, 62, 55, 65, 95, 102, 117, 150, 182, 127, 219, 299, 277, 309, 576]
44+
expect(
45+
findWeaknessRange(data, 127)
46+
).to.deep.equal([15, 25, 47, 40])
47+
})
48+
it('throws an error if no matching range found', () => {
49+
expect(() => { findWeaknessRange([1, 2, 3, 5, 8, 13], 50) }).to.throw('No range found matching target')
50+
})
51+
})
4152
})
4253
})

0 commit comments

Comments
 (0)