Skip to content

Commit e65e9c5

Browse files
feat(2020-day-09): check for valid data entry in XMAS encryption method
1 parent f07c78c commit e65e9c5

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

2020/day-09/xmasEncryption.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const isValid = (value, preamble) => {
2+
let valid = false
3+
4+
// Search for a combination of 2 entries that add up to `value`
5+
preamble.forEach((outer) => {
6+
preamble.forEach((inner) => {
7+
// match cannot use the same number twice
8+
if (outer !== inner && outer + inner === value) {
9+
console.debug(`Found matches ${outer} + ${inner} = ${value}`)
10+
valid = true
11+
}
12+
})
13+
})
14+
15+
return valid
16+
}
17+
18+
module.exports = {
19+
isValid
20+
}

2020/day-09/xmasEncryption.test.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/* eslint-env mocha */
2+
const { expect } = require('chai')
3+
const { isValid } = require('./xmasEncryption')
4+
5+
const range = (i) => { return i ? range(i - 1).concat(i) : [] }
6+
7+
describe('--- Day 9: Encoding Error ---', () => {
8+
describe('Part 1', () => {
9+
describe('isValid()', () => {
10+
it('checks if an entry is valid', () => {
11+
// first example
12+
const preamble = range(25)
13+
expect(isValid(26, preamble), '26 is valid').to.equal(true)
14+
expect(isValid(49, preamble), '49 is valid').to.equal(true)
15+
expect(isValid(100, preamble), '100 is larger than any sum').to.equal(false)
16+
expect(isValid(50, preamble), '50 not valid because cannot use the same number (25) twice').to.equal(false)
17+
// 2nd example
18+
// move 20 to start of the list, and then pop it off
19+
preamble.splice(preamble.indexOf(20), 1)
20+
// add 45 to the list
21+
preamble.push(45)
22+
expect(isValid(26, preamble), '26 is valid').to.equal(true)
23+
expect(isValid(65, preamble), '65 doesnt match any 2 values').to.equal(false)
24+
expect(isValid(64, preamble), '64 is valid').to.equal(true)
25+
expect(isValid(66, preamble), '65 is valid').to.equal(true)
26+
})
27+
})
28+
})
29+
})

0 commit comments

Comments
 (0)