Skip to content

Commit ade791b

Browse files
refactor(2018 day-11): skip invalid cells earlier to speed up tallies
1 parent aa02a97 commit ade791b

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

2018/day-11/fuel-cells.js

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,14 +63,23 @@ class Rack {
6363

6464
_tallySquare (idx, size) {
6565
let power = 0
66+
// Check if square will be off the panel by calculating the max index
67+
let maxIdx = idx + (size[0] - 1) + ((size[1] - 1) * this.size[0])
68+
if (maxIdx > this.cells.length) {
69+
return null
70+
}
71+
6672
for (let x = 0; x < size[0]; x++) {
6773
for (let y = 0; y < size[1]; y++) {
6874
let pointer = idx + x + (y * this.size[0])
69-
let dest = this.cells[pointer]
70-
if (!dest) {
75+
if (pointer > this.cells.length) {
7176
x = size[0]
7277
y = size[1]
7378
return null // break for speed on invalid squares
79+
}
80+
let dest = this.cells[pointer]
81+
if (!dest) {
82+
7483
}
7584
power += (dest) ? dest.power : 0
7685
}

2018/day-11/solution.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ powerBank.tallySquares(squareSize)
99
const answer = powerBank.getCellsByPower(squareSize)[0].coords
1010

1111
const anySizeSquares = []
12-
for (let dial = 1; dial <= 5; dial++) {
12+
for (let dial = 1; dial <= 300; dial++) {
13+
console.log(`Measuring power with dial at ${dial}`)
1314
powerBank.tallySquares([dial, dial])
1415
let bestOfSizeX = powerBank.getCellsByPower(squareSize)[0]
1516
anySizeSquares.push({

0 commit comments

Comments
 (0)