diff --git a/2022/23/README.md b/2022/23/README.md new file mode 100644 index 00000000..94464f15 --- /dev/null +++ b/2022/23/README.md @@ -0,0 +1,241 @@ +# Answers + +| Part 1 | Part 2 | +| ------ | ------ | +| `4254` | `992` | + +## --- Day 23: Unstable Diffusion --- + +You enter a large crater of gray dirt where the grove is supposed to be. All around you, plants you imagine were expected to be full of fruit are instead withered and broken. A large group of Elves has formed in the middle of the grove. + +"...but this volcano has been dormant for months. Without ash, the fruit can't grow!" + +You look up to see a massive, snow-capped mountain towering above you. + +"It's not like there are other active volcanoes here; we've looked everywhere." + +"But our scanners show active magma flows; clearly it's going _somewhere_." + +They finally notice you at the edge of the grove, your pack almost overflowing from the random _star_ fruit you've been collecting. Behind you, elephants and monkeys explore the grove, looking concerned. Then, the Elves recognize the ash cloud slowly spreading above your recent detour. + +"Why do you--" "How is--" "Did you just--" + +Before any of them can form a complete question, another Elf speaks up: "Okay, new plan. We have almost enough fruit already, and ash from the plume should spread here eventually. If we quickly plant new seedlings now, we can still make it to the extraction point. Spread out!" + +The Elves each reach into their pack and pull out a tiny plant. The plants rely on important nutrients from the ash, so they can't be planted too close together. + +There isn't enough time to let the Elves figure out where to plant the seedlings themselves; you quickly scan the grove (your puzzle input) and note their positions. + +For example: + + ....#.. + ..###.# + #...#.# + .#...## + #.###.. + ##.#.## + .#..#.. + + +The scan shows Elves `#` and empty ground `.`; outside your scan, more empty ground extends a long way in every direction. The scan is oriented so that _north is up_; orthogonal directions are written N (north), S (south), W (west), and E (east), while diagonal directions are written NE, NW, SE, SW. + +The Elves follow a time-consuming process to figure out where they should each go; you can speed up this process considerably. The process consists of some number of _rounds_ during which Elves alternate between considering where to move and actually moving. + +During the _first half_ of each round, each Elf considers the eight positions adjacent to themself. If no other Elves are in one of those eight positions, the Elf _does not do anything_ during this round. Otherwise, the Elf looks in each of four directions in the following order and _proposes_ moving one step in the _first valid direction_: + +* If there is no Elf in the N, NE, or NW adjacent positions, the Elf proposes moving _north_ one step. +* If there is no Elf in the S, SE, or SW adjacent positions, the Elf proposes moving _south_ one step. +* If there is no Elf in the W, NW, or SW adjacent positions, the Elf proposes moving _west_ one step. +* If there is no Elf in the E, NE, or SE adjacent positions, the Elf proposes moving _east_ one step. + +After each Elf has had a chance to propose a move, the _second half_ of the round can begin. Simultaneously, each Elf moves to their proposed destination tile if they were the _only_ Elf to propose moving to that position. If two or more Elves propose moving to the same position, _none_ of those Elves move. + +Finally, at the end of the round, the _first direction_ the Elves considered is moved to the end of the list of directions. For example, during the second round, the Elves would try proposing a move to the south first, then west, then east, then north. On the third round, the Elves would first consider west, then east, then north, then south. + +As a smaller example, consider just these five Elves: + + ..... + ..##. + ..#.. + ..... + ..##. + ..... + + +The northernmost two Elves and southernmost two Elves all propose moving north, while the middle Elf cannot move north and proposes moving south. The middle Elf proposes the same destination as the southwest Elf, so neither of them move, but the other three do: + + ..##. + ..... + ..#.. + ...#. + ..#.. + ..... + + +Next, the northernmost two Elves and the southernmost Elf all propose moving south. Of the remaining middle two Elves, the west one cannot move south and proposes moving west, while the east one cannot move south _or_ west and proposes moving east. All five Elves succeed in moving to their proposed positions: + + ..... + ..##. + .#... + ....# + ..... + ..#.. + + +Finally, the southernmost two Elves choose not to move at all. Of the remaining three Elves, the west one proposes moving west, the east one proposes moving east, and the middle one proposes moving north; all three succeed in moving: + + ..#.. + ....# + #.... + ....# + ..... + ..#.. + + +At this point, no Elves need to move, and so the process ends. + +The larger example above proceeds as follows: + + == Initial State == + .............. + .............. + .......#...... + .....###.#.... + ...#...#.#.... + ....#...##.... + ...#.###...... + ...##.#.##.... + ....#..#...... + .............. + .............. + .............. + + == End of Round 1 == + .............. + .......#...... + .....#...#.... + ...#..#.#..... + .......#..#... + ....#.#.##.... + ..#..#.#...... + ..#.#.#.##.... + .............. + ....#..#...... + .............. + .............. + + == End of Round 2 == + .............. + .......#...... + ....#.....#... + ...#..#.#..... + .......#...#.. + ...#..#.#..... + .#...#.#.#.... + .............. + ..#.#.#.##.... + ....#..#...... + .............. + .............. + + == End of Round 3 == + .............. + .......#...... + .....#....#... + ..#..#...#.... + .......#...#.. + ...#..#.#..... + .#..#.....#... + .......##..... + ..##.#....#... + ...#.......... + .......#...... + .............. + + == End of Round 4 == + .............. + .......#...... + ......#....#.. + ..#...##...... + ...#.....#.#.. + .........#.... + .#...###..#... + ..#......#.... + ....##....#... + ....#......... + .......#...... + .............. + + == End of Round 5 == + .......#...... + .............. + ..#..#.....#.. + .........#.... + ......##...#.. + .#.#.####..... + ...........#.. + ....##..#..... + ..#........... + ..........#... + ....#..#...... + .............. + + +After a few more rounds... + + == End of Round 10 == + .......#...... + ...........#.. + ..#.#..#...... + ......#....... + ...#.....#..#. + .#......##.... + .....##....... + ..#........#.. + ....#.#..#.... + .............. + ....#..#..#... + .............. + + +To make sure they're on the right track, the Elves like to check after round 10 that they're making good progress toward covering enough ground. To do this, count the number of empty ground tiles contained by the smallest rectangle that contains every Elf. (The edges of the rectangle should be aligned to the N/S/E/W directions; the Elves do not have the patience to calculate arbitrary rectangles.) In the above example, that rectangle is: + + ......#..... + ..........#. + .#.#..#..... + .....#...... + ..#.....#..# + #......##... + ....##...... + .#........#. + ...#.#..#... + ............ + ...#..#..#.. + + +In this region, the number of empty ground tiles is _`110`_. + +Simulate the Elves' process and find the smallest rectangle that contains the Elves after 10 rounds. _How many empty ground tiles does that rectangle contain?_ + +## --- Part Two --- +----------------- + +It seems you're on the right track. Finish simulating the process and figure out where the Elves need to go. How many rounds did you save them? + +In the example above, the _first round where no Elf moved_ was round _`20`_: + + .......#...... + ....#......#.. + ..#.....#..... + ......#....... + ...#....#.#..# + #............. + ....#.....#... + ..#.....#..... + ....#.#....#.. + .........#.... + ....#......#.. + .......#...... + + +Figure out where the Elves need to go. _What is the number of the first round where no Elf moves?_ diff --git a/2022/23/infinite-grid.js b/2022/23/infinite-grid.js new file mode 100644 index 00000000..c5e05a29 --- /dev/null +++ b/2022/23/infinite-grid.js @@ -0,0 +1,441 @@ +const Heap = require('heap'); + +/** + * @typedef {String} GridId - Two numbers separated by a comma. + * @example "10,5" + */ + +/** + * @typedef {Object} InfiniteGridConstructorOptions + * @property {?(x, y) => unknown} defaultFactory - Defaults to returning 0 for new coords + * @property {?Record} string_map - Map grid values to strings. + * @property {?String|unknown[][]} load - Initial grid to load. Can be a "2D" string (string with new lines), or a "2D" array. + * @property {?(v) => unknown} parseAs - When `load` is defined, this parses the cell in the split string. Defaults to `String`. + */ + +class InfiniteGrid { + /** + * @param {InfiniteGridConstructorOptions} options + */ + constructor({ defaultFactory = (x, y) => 0, string_map = {}, load: loadStr, parseAs } = {}) { + this.defaultFactory = defaultFactory.bind(this); + this.string_map = string_map; + this.grid = new Map(); + this.max_x = -Infinity; + this.min_x = Infinity; + this.max_y = -Infinity; + this.min_y = Infinity; + + if (loadStr) { + this.load(loadStr, parseAs); + } + } + + /** + * @param {Number} x + * @param {Number} y + * @returns {GridId} + */ + static toId(x, y) { + return `${x},${y}`; + } + + /** + * @param {GridId} id + * @param {Boolean} [return_as_object=false] + * @returns {{x: Number, y: Number} | [Number, Number]} + */ + static toCoords(id, return_as_object = false) { + let [x, y] = id.split(','); + x = parseInt(x, 10); + y = parseInt(y, 10); + return return_as_object ? { x, y } : [x, y]; + } + + /** + * @param {String} two_dimensional_string + * @returns {any[][]} + */ + static split(two_dimensional_string) { + return two_dimensional_string.split('\n').map((row) => row.split('')); + } + + static moveInDirection(x, y, direction) { + switch (direction) { + case 'N': + return [x, y - 1]; + case 'W': + return [x - 1, y]; + case 'E': + return [x + 1, y]; + case 'S': + return [x, y + 1]; + case 'NW': + return [x - 1, y - 1]; + case 'NE': + return [x + 1, y - 1]; + case 'SW': + return [x - 1, y + 1]; + case 'SE': + return [x + 1, y + 1]; + default: + throw new Error( + 'Invalid direction for moveInDirection. Valid directions are N, W, E, S, NW, NE, SW, SE' + ); + } + } + + reset() { + this.grid = new Map(); + this.max_x = -Infinity; + this.min_x = Infinity; + this.max_y = -Infinity; + this.min_y = Infinity; + return this; + } + + /** + * @param {String|unknown[][]} input + */ + load(input, parseAs = String) { + this.reset(); + let grid = input; + if (typeof input === 'string') { + grid = InfiniteGrid.split(input); + } + + for (let y = 0; y < grid.length; y++) { + for (let x = 0; x < grid[y].length; x++) { + this.set(x, y, parseAs(grid[y][x])); + } + } + } + + getRow(x, y, include_self = false) { + const self_id = InfiniteGrid.toId(x, y); + let cell_ids = Array(Math.abs(this.max_x - this.min_x) + 1) + .fill() + .map((_, i) => InfiniteGrid.toId(this.min_x + i, y)); + + if (!include_self) { + cell_ids = cell_ids.filter((id) => id !== self_id); + } + + return cell_ids.map((id) => this.grid.get(id)); + } + + getCol(x, y, include_self = false) { + const self_id = InfiniteGrid.toId(x, y); + let cell_ids = Array(Math.abs(this.max_y - this.min_y) + 1) + .fill() + .map((_, i) => InfiniteGrid.toId(x, this.min_y + i)); + + if (!include_self) { + cell_ids = cell_ids.filter((id) => id !== self_id); + } + + return cell_ids.map((id) => this.grid.get(id)); + } + + /** + * @todo The "wrap around" only really makes sense in a rectangular grid. + * Try to code in the cases where we have some cols/rows that are larger than others. + */ + getNeighbor(x, y, direction, { wrap_around = false } = {}) { + if (!this.inBounds(x, y)) { + return; + } + + const coord = InfiniteGrid.moveInDirection(x, y, direction); + const [new_x, new_y] = coord; + + if (this.inBounds(new_x, new_y)) { + return [this.get(new_x, new_y), coord]; + } else if (wrap_around) { + if (this.inBounds(new_x) && !this.inBounds(undefined, new_y)) { + if (direction === 'N') { + // Wrap to bottom + return [this.get(new_x, this.max_y), [new_x, this.max_y]]; + } else { + // Wrap to top + return [this.get(new_x, this.min_y), [new_x, this.min_y]]; + } + } else if (!this.inBounds(new_x) && this.inBounds(undefined, new_y)) { + if (direction === 'E') { + // Wrap to left + return [this.get(this.min_x, new_y), [this.min_x, new_y]]; + } else { + // Wrap to right + return [this.get(this.max_x, new_y), [this.max_x, new_y]]; + } + } + } + } + + /** + * @param {Number} x + * @param {Number} y + * @param {Boolean} [diagonals=false] + * @returns {Map} Return a map with optional keys N, W, E, S (and NW, NE, SW, SE if `diagonals` is true) if those neighbors are within the bounds of the map. + */ + neighbors(x, y, diagonals = false) { + const neighboring_cells = new Map(); + if (!this.inBounds(x, y)) { + return neighboring_cells; + } + + const neighbors_lookup = [ + ['N', [x, y - 1]], + ['W', [x - 1, y]], + ['E', [x + 1, y]], + ['S', [x, y + 1]], + ]; + + if (diagonals) { + neighbors_lookup.push( + ['NW', [x - 1, y - 1]], + ['NE', [x + 1, y - 1]], + ['SW', [x - 1, y + 1]], + ['SE', [x + 1, y + 1]] + ); + } + + for (let [key, coord] of neighbors_lookup) { + let [cx, cy] = coord; + if (this.inBounds(cx, cy)) { + neighboring_cells.set(key, { + id: InfiniteGrid.toId(cx, cy), + coord, + value: this.get(cx, cy), + }); + } + } + + return neighboring_cells; + } + + /** + * @param {Number} x + * @param {Number} y + * @param {any} value + */ + set(x, y, value) { + if (typeof x !== 'number' || typeof y !== 'number') { + throw new Error(`x and y must be numbers, got (${typeof x})${x} and (${typeof y})${y}`); + } + if (x < this.min_x) this.min_x = x; + if (x > this.max_x) this.max_x = x; + if (y < this.min_y) this.min_y = y; + if (y > this.max_y) this.max_y = y; + const id = InfiniteGrid.toId(x, y); + this.grid.set(id, value); + } + + /** + * @param {Number} x + * @param {Number} y + * @returns {any} + */ + get(x, y) { + const id = InfiniteGrid.toId(x, y); + if (!this.grid.has(id)) { + this.set(x, y, this.defaultFactory(x, y)); + } + return this.grid.get(id); + } + + delete(x, y) { + const id = InfiniteGrid.toId(x, y); + return this.grid.delete(id); + } + + /** + * @param {RegExp|any} value + * @param {Boolean} [as_coords] - When true, the 2nd element of each array element returned is an Array of `[x, y]` number values, otherwise are string IDs. + * @returns {Array<[any,GridId|Coord]>} - Returns an Array, the first value matching the cell found, and the 2nd the coords or ID. + */ + findAll(value, as_coords = true) { + const found = []; + for (let [id, cell] of this.grid) { + const check = value instanceof RegExp ? value.test(cell) : value === cell; + if (check) { + found.push([cell, as_coords ? InfiniteGrid.toCoords(id) : id]); + } + } + + return found; + } + + inBounds(x, y) { + if (x !== undefined && y !== undefined) { + return x >= this.min_x && x <= this.max_x && y >= this.min_y && y <= this.max_y; + } else if (x !== undefined && y === undefined) { + return x >= this.min_x && x <= this.max_x; + } else if (x === undefined && y !== undefined) { + return y >= this.min_y && y <= this.max_y; + } + } + + clone({ empty = false } = {}) { + const infinite_grid_clone = new InfiniteGrid(); + const new_map = new Map(); + if (!empty) { + for (let [key, val] of this.grid) { + new_map.set(key, typeof val === 'object' ? JSON.parse(JSON.stringify(val)) : val); + } + } + infinite_grid_clone.defaultFactory = this.defaultFactory.bind(this); + infinite_grid_clone.string_map = JSON.parse(JSON.stringify(this.string_map)); + infinite_grid_clone.grid = new_map; + infinite_grid_clone.max_x = this.max_x; + infinite_grid_clone.min_x = this.min_x; + infinite_grid_clone.max_y = this.max_y; + infinite_grid_clone.min_y = this.min_y; + + return infinite_grid_clone; + } + + sum() { + let sum = 0; + for (let value of this.grid.values()) { + sum += value; + } + + return sum; + } + + /** + * Removes `value` from the grid and resizes the bounds + * @param {unknown} value + */ + prune(value) { + const cells_to_copy = new Map(); + for (let [id, cell] of this.grid) { + if (cell !== value) { + cells_to_copy.set(id, cell); + } + } + + this.grid.clear(); + for (let [id, cell] of cells_to_copy) { + this.grid.set(id, cell); + } + + this.resize(); + } + + resize() { + this.max_x = -Infinity; + this.min_x = Infinity; + this.max_y = -Infinity; + this.min_y = Infinity; + + for (let id of this.grid.keys()) { + let [x, y] = InfiniteGrid.toCoords(id); + if (x < this.min_x) this.min_x = x; + if (x > this.max_x) this.max_x = x; + if (y < this.min_y) this.min_y = y; + if (y > this.max_y) this.max_y = y; + } + } + + buildDijkstrasFrontier(from_x, from_y) { + const from_id = InfiniteGrid.toId(from_x, from_y); + + // Sort our frontier by its priority, so we pick nodes to visit that have the lowest cost. + const frontier = new Heap((node_a, node_b) => node_a.priority - node_b.priority); + frontier.push({ id: from_id, priority: 0 }); + + const came_from = new Map([[from_id, null]]); + const cost_so_far = new Map([[from_id, 0]]); + while (!frontier.empty()) { + const current = frontier.pop(); + + const [current_x, current_y] = InfiniteGrid.toCoords(current.id); + + for (let next of this.neighbors(current_x, current_y).values()) { + const new_cost = cost_so_far.get(current.id) + next.value; + if (!cost_so_far.has(next.id) || new_cost < cost_so_far.get(next.id)) { + cost_so_far.set(next.id, new_cost); + frontier.push({ id: next.id, priority: new_cost }); + came_from.set(next.id, current.id); + } + } + } + + return came_from; + } + + getShortestWeightedPath(from_x, from_y, to_x, to_y, { include_from = true } = {}) { + const from_id = InfiniteGrid.toId(from_x, from_y); + const to_id = InfiniteGrid.toId(to_x, to_y); + const came_from = this.buildDijkstrasFrontier(from_x, from_y); + let current = to_id; + + let path = []; + while (current !== from_id) { + path.push(current); + current = came_from.get(current); + } + + if (include_from) { + path.push(from_id); + } + path.reverse(); + return path; + } + + toGrid() { + let grid = []; + for (let y = this.min_y; y <= this.max_y; y++) { + let row = []; + for (let x = this.min_x; x <= this.max_x; x++) { + let cell = this.get(x, y); + row.push(cell); + } + grid.push(row); + } + + return grid; + } + + toJSON() { + return this.toGrid(); + } + + toString() { + let grid = this.toGrid(); + let rows = ''; + for (let y = 0; y < grid.length; y++) { + let row = ''; + for (let x = 0; x < grid[y].length; x++) { + let cell = grid[y][x]; + let cell_string = cell in this.string_map ? this.string_map[cell] : String(cell); + row += cell_string; + } + rows += rows.length ? '\n' + row : row; + } + + return rows; + } + + *[Symbol.iterator]() { + yield* this.grid.entries(); + } + + entries() { + return this.grid.entries(); + } + + values() { + return this.grid.values(); + } + + keys() { + return this.grid.keys(); + } +} + +module.exports = { + InfiniteGrid, +}; diff --git a/2022/23/input.js b/2022/23/input.js new file mode 100644 index 00000000..e78dcd22 --- /dev/null +++ b/2022/23/input.js @@ -0,0 +1,34 @@ +const path = require('path'); +const fs = require('fs'); + +const input = fs.readFileSync(path.join(__dirname, 'input.txt'), 'utf8').toString().trim(); + +module.exports = { + input, + sampleInputTrimmed: ` +....#.. +..###.# +#...#.# +.#...## +#.###.. +##.#.## +.#..#..`, + sampleInput: `.............. +.............. +.......#...... +.....###.#.... +...#...#.#.... +....#...##.... +...#.###...... +...##.#.##.... +....#..#...... +.............. +.............. +..............`, + sampleInputSmall: `..... +..##. +..#.. +..... +..##. +.....`, +}; diff --git a/2022/23/input.txt b/2022/23/input.txt new file mode 100644 index 00000000..44cae66b --- /dev/null +++ b/2022/23/input.txt @@ -0,0 +1,75 @@ +..###.#####....####.......###.####.#.....##..#.##.....#.##..#.#.........#.# +.##...#.##...#.##.######.######.#######.#####.#..##...#..#....#.#.#.#...#.. +#.#.#......#.#..#...#..###..###.#####..#####.#.....##.#.#...##.#.###..#..## +#..##...#####..##...#.##.#.##..##..#...#.###.###..##..####.####.#..#...##.. +#.#...#..#.#####..#####..##.##...#....#.###.....##.#..###....#.#.##..#####. +#.#..#.#.#..#....#...#..##.#.##...#####.#..###..#.#.#.##...#.##.#.##..#..#. +#.####..#...####..........##.#.#....#.#.#...###.#......#.######.#..##.###.. +######...#.#.######.........#.##..####.##..#.#.##....##.#.##.#.#..##.##...# +.##.#.#.###..#.#.##.#..###..##..##.#.###...#..###..#..###.####...###.##.#.. +#.#..#.....##.#.#..##...##..####.####...##..#....##.##.#....#.#..#.#.#..### +..#.###..#..######.##..#.#..#.#..#.#####.##.####...##.#....#.####....##.##. +.......#.###..#.##.#.##....#....#.#...##....####..#.#.#...###.##..#.#.#.### +.####.####..#..##...##...##.####.#.#.#.#.####..##..###.##...##.##....##..#. +###..##.###..###...###....###....####...#..#######....#.#.#.#....###..##..# +##.###..######....#.##..####..#...##..#.#...#..#..#.#.#.#..#.###.###.###### +#....#.#....#.#...####...#.#..##...##.#..#..#.#############....#.###....#.. +#..##.#######.#..###...##...#...####.#.####.....#.....#...##.#.####.##.#.## +#.#.#..###.######.#.###.#.#####.........##....###.#####..###.#.####.#..###. +####.#.#..#.####....#######...###.#.#####.#..#.....###.#.###..#.#..###..### +##..#.#..#.....###.####..###.#...##.#....#..#..#.##....#..#.#...#.#.###..#. +########..#.....##.##.####..#####....##.#.####.###.....#.......###.##....#. +#..#.#######..#...###..#.###..###...##..#.###.##..###..#......##.###..##..# +##..###.#..#.###...##..##.#.#...#.###.##.###.#..#..#...###..#.#####..##.... +##.#.#...#.#..#.#.###....#.#.#.#..#..#.###..#..#.#..##.#####.#..##.######.. +##..#####..........##.##...#.....#..##.#####..##.##.#..#..#####....##...### +#..###.#.##.##..##...######..#.###..#.#.#..###.###.####.##.##.#...##..####. +#.###..###..##.#####..####.....##.#.....#..#.#...#..####.#.######.##.#.#..# +.##....#.#.##...#.#.#...##..#.....#...##..##..####.#..####.##.#.#.#..#.###. +########..#.#.#...#...##...##....##..#.....#.......##..#.#######.##.#....## +.#..#...##.#.##..##.#..#..#.#####.#.#.#..#.....##.##.....##.#.##.##.#.#.### +#..####.##.###..#...#..#.##.#########.#######...#...#..##..#.....###..#..## +##....###..#.#....##...##.####.######..####....###....########..##...###..# +.##...##.#.#.##..###.##.###..#.#..#......#######..#..##....#....###.##..#.. +##..###...###..#.###.#.##.###.#...#.#.#.####.#.####..#.#..###..#####...#### +#####...######.#.#..##.#.###.#.#.#...###......#.#..##..#..##...##.######### +#..#.##.....#.#####.##.....#.#..#.###.#..##.##..##..##..##..#.#..#..##.#### +..###.#...#.##...##.#.....#.#####..#.#..#...#.####...#.#####.#######..#.### +..#.##..#.#..#.###.##..#...#.#....##.....#..#.#...#.##..###.###.##..###..#. +..#.#.#..#....#.#..##..#......#..#...#####.##.....#.##..##.#####.#.#...#... +.#..#.....########......##.####..#..#...##.#.###...#.#...##..#####.#..##... +#..#.#.##.#......##.#......#..####.###....#.#.##..##.....#.#.##.#####..##.# +...#...###...####..#.#.#......#.#..#..##.##..###.#...#.###..#..#...###.###. +##.##.#.........#..#..#....#..#......##.#.######.#..#.#...##.#.##..#..#..#. +.#.##..####.#..##.##....#....###...##..#.#..#.#.##.####...##..#..####....#. +.....##.#..##.#.###.....####..###.##.###.....##..##...#.#..#.##..#.##.#.#.# +##.##.#.#..........#..#.####.#..##.#..#.#.###....###.###.#.##.###.#.....#.. +#..#.#.##.##..##.###..###..#.#..#..##.....#......#####.#..###.#.#.....####. +.##....###..##...#..#.######.####..#.##....#..##.#..####..##....#.....#.##. +..#.#.##....#...#.#..#.....#...###.#.#.#####...####.###.##...###.###.#.##.. +#..###.#...##.#.#.#.#..#.#..#.##...#######....#.####.####.##.#######..##### +..#..#.####...#....#...#......#...#..##.#...#...#######..#..#.#####.###..## +.#.#.###...##.###....#.....####.##.####...#...........###..##...####.#..##. +.###.####.#..#....###.#.##.#.#####..#.#######.#..##.#.###...#.#..####.#.#.. +..###.#....###.#.....###.#####.#.##.#..###.####.....#..#..#..##.....##.#.## +##.##.##...#....##..###.##.#...#......#.....##.#....#.#...##..##...#..####. +.###.....#....##..#####.##..#.#.....#..###..#####.#.#...##..##....#.###.#.. +.##..####..#....##.#####.#.#..#.#.#.##.#..#.#....###.##.###..#....######.#. +#.###..#...##.##...####..##....#.##..###.....#.....#..##.#...###..###.....# +..#.#.##...##.##.##..#.#.##.##...##..#.###.#...######.....#.....#.....#.##. +#.#.#.##.#.#.##.###...####...####..#.....###.#..###.....#..##.#...#.###..## +#..###.##.#####..#.##...#..###.#.#.#.#....##...###.#..#####.#......##..#.#. +##.#.##...##.#####...#...#.#...#..##.##.#...#.###..##...##..##.#..##.#.###. +....####....##..#....##.#...##.#.....##.####.#..#......#.##.##....#.#..#.## +#.#.#####.##...#..#.#....#.####..#####....#.###..######..##....####..#.#### +.##.#...##..####.#....##..##....#....##.#.#....#....#.##......##....#...#.# +####..#..#.#.#.#.#..###.###.##..##..#..#.####...##.#..####.........#..#.#.. +.##...#..###.#.#.#.#.###.#.#.#########........###.#.#..#.....####..#..#.#.# +##..###..#.##......#.#.....#....#....#..#####.#.####..###.#.###....#.##.#.. +#.#.#.##...#.....#.#..###.#..######.#..##.#.###..#.####..###.#....##.####.. +.##...#..#..###.###.........##....##...#.###..#..#.#.#.#.#.###......##..##. +.##.##.##..#.######..#.##..##.#...#.##.#..###.#....#..#####.##..#..#.###... +..####.##.#..#..##..##...####.######.##.#.....##.#....#....###.##.##....### +.##......#.....#.#..#.#.##....#.#.#.####...#...##...##...#.##.#.#.#.##...## +.##.#######..#.#..#.#..##..#.#....##...#####...##..#.......##...##..##..#.# +#...#.#..#.###.#.##....##..#...#.#..##.###.......##.#.....######..######### diff --git a/2022/23/part-one.js b/2022/23/part-one.js new file mode 100644 index 00000000..865107a0 --- /dev/null +++ b/2022/23/part-one.js @@ -0,0 +1,33 @@ +const { input } = require('./input'); +const { InfiniteGrid } = require('./infinite-grid'); +const { PlantSteps, ELF, GROUND } = require('./plant-steps'); + +const grid = new InfiniteGrid({ + load: input, + defaultFactory: () => GROUND, + parseAs: (cell) => (cell === '#' ? ELF : GROUND), + string_map: { [GROUND]: '.', [ELF]: '#' }, +}); + +const game = new PlantSteps(grid); +// console.log('== Initial State ==\n'); +for (let i = 0; i < 10; i++) { + // console.log(game.grid.toString()); + game.tickRound(); + // console.log(`\n== End of Round ${i + 1} ==\n`); +} +// console.log(game.grid.toString()); + +game.grid.prune(GROUND); + +const gridJSON = game.grid.toJSON(); +let count = 0; +for (let y = 0; y < gridJSON.length; y++) { + for (let x = 0; x < gridJSON[y].length; x++) { + let cell = gridJSON[y][x]; + if (cell === GROUND) { + count++; + } + } +} +console.log(count); diff --git a/2022/23/part-two.js b/2022/23/part-two.js new file mode 100644 index 00000000..4c868984 --- /dev/null +++ b/2022/23/part-two.js @@ -0,0 +1,20 @@ +const { input } = require('./input'); +const { InfiniteGrid } = require('./infinite-grid'); +const { PlantSteps, ELF, GROUND } = require('./plant-steps'); + +const grid = new InfiniteGrid({ + load: input, + defaultFactory: () => GROUND, + parseAs: (cell) => (cell === '#' ? ELF : GROUND), + string_map: { [GROUND]: '.', [ELF]: '#' }, +}); + +const game = new PlantSteps(grid); + +/** + * This runs fairly slow, around ~8s, because I don't have a good mechanism to just loop + * over the ELF cells in each tick, instead I loop over all cells and only operate on + * the ELF ones. + */ +const rounds = game.run({ pruneEveryNRounds: 0 }); +console.log(rounds); diff --git a/2022/23/plant-steps.js b/2022/23/plant-steps.js new file mode 100644 index 00000000..4b489c00 --- /dev/null +++ b/2022/23/plant-steps.js @@ -0,0 +1,120 @@ +const { InfiniteGrid } = require('./infinite-grid'); + +function neighborsMapIsEmpty(map) { + for (let { value } of map.values()) { + if (value) { + return false; + } + } + + return true; +} + +const ELF = 1; +const GROUND = 0; + +class PlantSteps { + /** + * @param {InfiniteGrid} grid + */ + constructor(grid) { + this.grid = grid; + + // 1. If there is no Elf in the N, NE, or NW adjacent positions, the Elf proposes moving north one step. + // 2. If there is no Elf in the S, SE, or SW adjacent positions, the Elf proposes moving south one step. + // 3. If there is no Elf in the W, NW, or SW adjacent positions, the Elf proposes moving west one step. + // 4. If there is no Elf in the E, NE, or SE adjacent positions, the Elf proposes moving east one step. + this.proposals = [ + { check: ['N', 'NE', 'NW'], moveInDir: 'N' }, + { check: ['S', 'SE', 'SW'], moveInDir: 'S' }, + { check: ['W', 'NW', 'SW'], moveInDir: 'W' }, + { check: ['E', 'NE', 'SE'], moveInDir: 'E' }, + ]; + this.round = 0; + } + + tickRound() { + // `null` values mean two elves tried to move to the same spot + const elf_movement_destinations = new Map(); + for (let [id, cell] of this.grid) { + if (cell === GROUND) { + continue; + } + + const coord = InfiniteGrid.toCoords(id); + const elf_neighbors = this.grid.neighbors(...coord, true); + + if (!neighborsMapIsEmpty(elf_neighbors)) { + for (let i = 0; i < this.proposals.length; i++) { + const index = (i + this.round) % this.proposals.length; + const proposal = this.proposals[index]; + + const proposal_elves_size = proposal.check.reduce((neighborSum, dir) => { + const dir_value = elf_neighbors.get(dir)?.value || GROUND; + return neighborSum + dir_value; + }, 0); + + if (!proposal_elves_size) { + // Try to move in this dir + const dest_coord = InfiniteGrid.moveInDirection( + ...coord, + proposal.moveInDir + ); + const dest_id = InfiniteGrid.toId(...dest_coord); + const already_taken = elf_movement_destinations.get(dest_id); + + if (already_taken === undefined) { + // Not taken, place our elf there! + elf_movement_destinations.set(dest_id, coord); + } else { + // We already tried to move there, so null it out so noone moves there + elf_movement_destinations.set(dest_id, null); + } + + // We found a proposal, break our loop + break; + } + } + } + } + + // 2nd half, move the elves + let some_elf_moved = false; + for (let [dest_id, origin_coord] of elf_movement_destinations) { + if (origin_coord === null) { + continue; + } + + some_elf_moved = true; + const elf_char = this.grid.get(...origin_coord); + this.grid.set(...InfiniteGrid.toCoords(dest_id), elf_char); + + /** + * Interestingly, if I'd `delete()` the `origin_coord`, I actually + * get worse performance! I think its because deleting those values requires + * a lot of resizing of my grid, which is slow. So setting the origin to + * GROUND is actually faster. + */ + this.grid.set(...origin_coord, GROUND); + } + + this.round++; + + return some_elf_moved; + } + + run() { + let some_elf_moved; + do { + some_elf_moved = this.tickRound(); + } while (some_elf_moved); + + return this.round; + } +} + +module.exports = { + PlantSteps, + ELF, + GROUND, +}; diff --git a/README.md b/README.md index fee5eb96..181448dd 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ of manual tinkering. ## 2022 Puzzles List -Completed: **13 / 25** (52%) +Completed: **14 / 25** (56%) * [✅ Day 1](2022/1/) * [✅ Day 2](2022/2/) @@ -34,6 +34,16 @@ Completed: **13 / 25** (52%) * [✅ Day 11](2022/11/) * [✅ Day 12](2022/12/) * [✅ Day 13](2022/13/) +* Day 14 +* Day 15 +* Day 16 +* Day 17 +* Day 18 +* Day 19 +* Day 20 +* Day 21 +* Day 22 +* [✅ Day 23](2022/23/) ## 2021 Puzzles List