Skip to content

Commit bd74885

Browse files
fix[2020-day-01]: find the exact number of desired expense records
If the desired number is 3, don't stop if 2 meet the checksum requirements.
1 parent f7a9dea commit bd74885

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

2020/day-01/expenseValidation.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ const validateRecords = (records, checksum = 2020, goal = 2) => {
2323
this.depth = this.depth || 1 // depth tracking starts at level 1
2424
this.tracker = this.tracker || 0 // for basic sums, start counter at 0
2525
const subTotal = this.tracker + record
26-
// Found a match, don't keep searching!
27-
if (subTotal === this.target) {
26+
// Found a match in the specified with desired qty of results, don't keep searching!
27+
if (subTotal === this.target && this.depth >= goal) {
2828
results.push(record)
2929
return true
3030
}
@@ -44,7 +44,7 @@ const validateRecords = (records, checksum = 2020, goal = 2) => {
4444
depth: this.depth + 1,
4545
tracker: this.tracker + record
4646
})
47-
// Children matched, so record this one as well
47+
// Propogate maches back up the recursion chain, capturing each
4848
if (res) {
4949
results.push(record)
5050
return true

2020/day-01/expenseValidation.test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,16 @@ describe('--- 2020 Day 1: Report Repair ---', () => {
2323
expect(testData.indexOf(result)).to.be.greaterThan(-1)
2424
})
2525
})
26+
it('it can find a specified number of records adding up to 2020', () => {
27+
const expected = [979, 366, 675]
28+
const results = validateRecords(testData, undefined, 3)
29+
// Should same number of results
30+
expect(results.length).to.equal(expected.length)
31+
// Result order is unnecessary, but all expected hould be in the result set
32+
expected.forEach(result => {
33+
expect(testData.indexOf(result)).to.be.greaterThan(-1)
34+
})
35+
})
2636
it('it supports specifying an alternate checksum', () => {
2737
const arrSum = (arr) => arr.reduce((x, y) => x + y, 0)
2838
const expected = [testData[3], testData[5]]

0 commit comments

Comments
 (0)