Skip to content

Commit 694cdca

Browse files
committed
Day 22: Keep one coordinate instead of two
From 1.7 seconds to 1.5 seconds. I wonder if the speedup is from doing fewer reads (`g[pos]` instead of `g[y][x]`) or fewer additions (adding `pos` instead of both `y` and `x`)
1 parent e45a9b6 commit 694cdca

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

22_sporifica_virus.rb

+8-6
Original file line numberDiff line numberDiff line change
@@ -107,23 +107,26 @@ def infects(s, n, states)
107107
# (and because of a 2x2 grid, padding needed is halved)
108108
pad = Math.log(n, 10).ceil * 25
109109
g = grid(s, pad, states.index(:clean), states.index(:infected))
110+
width = g[0].size
110111

111112
# If (s.size / 2) was even, grid got shifted down.
112113
# If odd, it did not get shifted down; must subtract 1.
113114
y = x = g.size / 2 - sub_x
115+
pos = y * width + x
114116
infects = 0
115117

118+
g.flatten!
119+
116120
# lower (sub_y = 1) always, by construction
117121
# left (sub_x = 0) if x even, right (sub_x = 1) if x odd
118122
# direction: up (0)
119123
cache_key = 1 << 3 | sub_x << 2 | 0
120124

121-
dy = [-1, 0, 1, 0].freeze
122-
dx = [0, 1, 0, -1].freeze
125+
dpos = [-width, 1, width, -1].freeze
123126

124127
loop {
125-
cache_key = g[y][x] << 4 | cache_key & 0xf
126-
steps, infects_to_add, infect_times, g[y][x], cache_key = cache[cache_key]
128+
cache_key = g[pos] << 4 | cache_key & 0xf
129+
steps, infects_to_add, infect_times, g[pos], cache_key = cache[cache_key]
127130

128131
n -= steps
129132
if n < 0
@@ -132,8 +135,7 @@ def infects(s, n, states)
132135
end
133136

134137
infects += infects_to_add
135-
y += dy[cache_key & 3]
136-
x += dx[cache_key & 3]
138+
pos += dpos[cache_key & 3]
137139
}
138140
end
139141

0 commit comments

Comments
 (0)