-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathgrid.js
288 lines (249 loc) · 7.05 KB
/
grid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/**
* Rotates a square 2d array 90 degrees clockwise in place
* @link https://code.likeagirl.io/rotate-an-2d-matrix-90-degree-clockwise-without-create-another-array-49209ea8b6e6
*/
function rotate(matrix) {
const n = matrix.length;
const x = Math.floor(n / 2);
const y = n - 1;
for (let i = 0; i < x; i++) {
for (let j = i; j < y - i; j++) {
k = matrix[i][j];
matrix[i][j] = matrix[y - j][i];
matrix[y - j][i] = matrix[y - i][y - j];
matrix[y - i][y - j] = matrix[j][y - i];
matrix[j][y - i] = k;
}
}
}
/**
* @param {Array<Array>} grid_rule
* @param {Boolean} [reflect_y=false]
* @returns {String}
*/
function joinGridRule(grid_rule, reflect_y = false) {
/**
* Use loops and string concatentations to prevent intermediary arrays
* from being created, improving run-time.
*
* A cleaner, "one liner" might look like:
*
* return (reflect_y
* ? grid_rule.map((row) => row.join(''))
* : grid_rule.map((row) => row.join('')).reverse()
* ).join('/');
*/
let result = '';
const processRow = (y) => {
let row = '';
for (let x = 0; x < grid_rule[y].length; x++) {
row += grid_rule[y][x];
}
if (result) {
result += '/' + row;
} else {
result += row;
}
};
if (reflect_y) {
for (let y = grid_rule.length - 1; y >= 0; y--) {
processRow(y);
}
} else {
for (let y = 0; y < grid_rule.length; y++) {
processRow(y);
}
}
return result;
}
/*
TRANSFORMATION EXAMPLES
0° 90° 180° 270°
-- --- ---- ----
#. .. .. .#
.. #. .# ..
y
--
.. #. .. ..
#. .. #. .#
x
--
.# .. .. #.
.. .# #. ..
0° 90° 180° 270°
-- --- ---- ----
### ##. .#. ..#
..# #.# #.. #.#
.#. #.. ### .##
y
--
.#. #.. ### .##
..# #.# #.. #.#
### ##. .#. ..#
x
--
### .## .#. #..
#.. #.# ..# #.#
.#. ..# ### ##.
*/
/**
* Given a "raw" rule string and a lookup object reference, split the
* expansion output to an array, then save that array across all possible
* transformations of the rule input.
* @param {String} rule_raw - e.g. `../.. => ..#/#.#/###`
* @param {Object} lookup - Applies all rules, including transformations, to the `lookup` in place
* @example
* {
* "#./..": [".#.", "#..", "###"],
* ...
* }
*/
function applyTransformations(rule_raw, lookup) {
let [rule_input, rule_output] = rule_raw.split(' => ');
rule_output = rule_output.split('/');
lookup[rule_input] = rule_output;
let rule_input_grid = rule_input.split('/').map((row) => row.split(''));
/**
* Can't find concrete math on this, but naturally there is a symmetry group
* going on here. After diong some rotation and reflections by hand, it looks
* like roating 0, 90, 180, and 270, plus reflecting each of those over any axis
* (whichever one is easier) will generate all possible states, with potential
* duplicates. Assigning those within my lookup will remove those duplicates
* automatically.
*/
for (let r = 0; r < 4; r++) {
lookup[joinGridRule(rule_input_grid)] = rule_output;
lookup[joinGridRule(rule_input_grid, true)] = rule_output;
rotate(rule_input_grid);
}
// Useful for debugging, but not required since I'm updating the lookup in place
return lookup;
}
function convertInputToRulesObject(input) {
let rules_lookup = {};
let rules = input.split('\n');
for (let rule_raw of rules) {
// Makes change to `rules_lookup` in place
applyTransformations(rule_raw, rules_lookup);
}
return rules_lookup;
}
/**
* Returns a 2d square array from a grid, given an x/y offset ([0,0] is the upper left corner)
* @param {Array<Array>} grid
* @param {Number} x_offset
* @param {Number} y_offset
* @param {Number} size Size of the subgrid to pick out
* @returns {Array}
*/
function pickSubgrid(grid, x_offset, y_offset, size) {
let subgrid = [];
for (let y = y_offset; y < y_offset + size; y++) {
let row = [];
for (let x = x_offset; x < x_offset + size; x++) {
row.push(grid[y][x]);
}
subgrid.push(row);
}
return subgrid;
}
/**
* Returns a string representation of our grid, to be immediately used as an expansion rule
* @param {Array<Array>} grid
* @param {Number} x_offset
* @param {Number} y_offset
* @param {Number} size Size of the subgrid to pick out
* @returns {String}
*/
function pickSubgridAsRule(grid, x_offset, y_offset, size) {
let subgrid = '';
for (let y = y_offset; y < y_offset + size; y++) {
for (let x = x_offset; x < x_offset + size; x++) {
subgrid += grid[y][x];
}
if (y < y_offset + size - 1) {
subgrid += '/';
}
}
return subgrid;
}
/**
* @param {Array<Array>} grid - A 2d grid of our '#' and '.' pixels
* @param {Object} rules
*/
function expandGrid(grid, rules) {
let new_grid = [];
/**
* If divisible by 3, 3x3 -> 4x4
* If divisible by 2, 2x2 -> 3x3
*/
let intial_size = grid.length % 2 === 0 ? 2 : 3;
let expansion_size = intial_size + 1;
let chunks = Math.floor(grid.length / intial_size);
// Need to iterate over x/y chunks
for (let y_chunk = 0; y_chunk < chunks; y_chunk++) {
let y_offset = y_chunk * intial_size;
/**
* But, when saving our new grid, save cols as
* concatenated strings. So the rows need to be offset
* for the newly expanded array we are creating.
*/
let y_resized_offset = y_chunk * expansion_size;
for (let x_chunk = 0; x_chunk < chunks; x_chunk++) {
let x_offset = x_chunk * intial_size;
// Slightly more optimized to use `pickSubgridAsRule`. Original code shown below
// let subgrid = pickSubgrid(grid, x_offset, y_offset, intial_size);
// let subgrid_as_rule = joinGridRule(subgrid);
let subgrid_as_rule = pickSubgridAsRule(grid, x_offset, y_offset, intial_size);
let expansion = rules[subgrid_as_rule];
for (let y = 0; y < expansion.length; y++) {
let expansion_row = expansion[y];
if (new_grid[y_resized_offset + y] === undefined) {
new_grid[y_resized_offset + y] = '';
}
new_grid[y_resized_offset + y] += expansion_row;
}
}
}
// `new_grid` is an array of strings, so split the strings to get a 2D array
let final_new_grid = new_grid.map((row) => row.split(''));
return final_new_grid;
}
// For the puzzle, starting point is always the same
const STARTING_GRID = `.#.
..#
###`
.split('\n')
.map((row) => row.split(''));
function iterativelyExpandGrid(input, iterations, grid = STARTING_GRID) {
let rules = convertInputToRulesObject(input);
for (let i = 0; i < iterations; i++) {
let new_grid = expandGrid(grid, rules);
grid = new_grid;
}
return grid;
}
/**
* Counts the number of "on" and "off" pixels.
* "On" is denoted via a '#' character.
* "Off" is denoted via a '.' character.
* @param {Array<Array>} grid
* @returns {Object<Number>} Returns `{ pixels_on, pixels_off }`
*/
function countPixelsInGrid(grid) {
// Assumes a square grid
let total_pixels = grid.length * grid.length;
let pixels_on = grid
.map((row) => row.reduce((sum, cell) => sum + (cell === '#' ? 1 : 0), 0))
.reduce((a, b) => a + b);
let pixels_off = total_pixels - pixels_on;
return {
pixels_on,
pixels_off,
};
}
module.exports = {
STARTING_GRID,
iterativelyExpandGrid,
countPixelsInGrid,
};