Skip to content

Commit 725e880

Browse files
perf(2020-day-13): speed up search by exiting out of times as soon as there is a mismatch
1 parent 93c6790 commit 725e880

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

2020/day-13/busSchedules.js

+13-4
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,19 @@ const findSequentialTime = (schedule) => {
2828
// If we get an array the same length as the routes array, that means all routes matched
2929
while (result.length < routes.length) {
3030
x += routes[0]
31-
result = routes.filter((route, idx) => {
32-
if (route === 'x') { return true } // x doesn't matter
33-
return ((x + idx) % route === 0) // Route is sequentially +1 above the previous route
34-
})
31+
// loop through the list looking for el mod = idx
32+
let matches = true
33+
let i = 0
34+
while (i < routes.length && matches === true) {
35+
if (routes[i] === 'x') { // "x" doesn't matter
36+
i++
37+
} else if ((x + i) % routes[i] === 0) { // Route is sequentially +1 above the previous route
38+
i++
39+
} else {
40+
matches = false
41+
}
42+
}
43+
if (matches) { result = routes }
3544
}
3645
console.debug(`Found a match ${x}`)
3746
return x

2020/day-13/busSchedules.test.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ describe('--- Day 13: Shuttle Search ---', () => {
3030
describe('Part 2', () => {
3131
describe('findSequentialTime', () => {
3232
it('finds a sequential time where the busses all depart sequentially', () => {
33-
// expect(findSequentialTime('7,13,x,x,59,x,31,19')).to.equal(1068781)
33+
expect(findSequentialTime('7,13,x,x,59,x,31,19')).to.equal(1068781)
3434
expect(findSequentialTime('17,x,13,19')).to.equal(3417)
3535
expect(findSequentialTime('67,7,59,61')).to.equal(754018)
3636
expect(findSequentialTime('67,x,7,59,61')).to.equal(779210)

0 commit comments

Comments
 (0)