1 billion blocks

This commit is contained in:
eleith 2022-12-23 21:36:23 -08:00
parent 59bb9fff77
commit d7571f643e
4 changed files with 746 additions and 0 deletions

355
17/README.md Normal file
View File

@ -0,0 +1,355 @@
--- Day 17: Pyroclastic Flow ---
Your handheld device has located an alternative exit from the cave for you and the elephants. The ground is rumbling almost continuously now, but the strange valves bought you some time. It's definitely getting warmer in here, though.
The tunnels eventually open into a very tall, narrow chamber. Large, oddly-shaped rocks are falling into the chamber from above, presumably due to all the rumbling. If you can't work out where the rocks will fall next, you might be crushed!
The five types of rocks have the following peculiar shapes, where # is rock and . is empty space:
####
.#.
###
.#.
..#
..#
###
#
#
#
#
##
##
The rocks fall in the order shown above: first the - shape, then the + shape, and so on. Once the end of the list is reached, the same order repeats: the - shape falls first, sixth, 11th, 16th, etc.
The rocks don't spin, but they do get pushed around by jets of hot gas coming out of the walls themselves. A quick scan reveals the effect the jets of hot gas will have on the rocks as they fall (your puzzle input).
For example, suppose this was the jet pattern in your cave:
> > > <<><>><<<>><>>><<<>>><<<><<<>><>><<>>
In jet patterns, < means a push to the left, while > means a push to the right. The pattern above means that the jets will push a falling rock right, then right, then right, then left, then left, then right, and so on. If the end of the list is reached, it repeats.
The tall, vertical chamber is exactly seven units wide. Each rock appears so that its left edge is two units away from the left wall and its bottom edge is three units above the highest rock in the room (or the floor, if there isn't one).
After a rock appears, it alternates between being pushed by a jet of hot gas one unit (in the direction indicated by the next symbol in the jet pattern) and then falling one unit down. If any movement would cause any part of the rock to move into the walls, floor, or a stopped rock, the movement instead does not occur. If a downward movement would have caused a falling rock to move into the floor or an already-fallen rock, the falling rock stops where it is (having landed on something) and a new rock immediately begins falling.
Drawing falling rocks with @ and stopped rocks with #, the jet pattern in the example above manifests as follows:
The first rock begins falling:
|..@@@@.|
|.......|
|.......|
|.......|
+-------+
Jet of gas pushes rock right:
|...@@@@|
|.......|
|.......|
|.......|
+-------+
Rock falls 1 unit:
|...@@@@|
|.......|
|.......|
+-------+
Jet of gas pushes rock right, but nothing happens:
|...@@@@|
|.......|
|.......|
+-------+
Rock falls 1 unit:
|...@@@@|
|.......|
+-------+
Jet of gas pushes rock right, but nothing happens:
|...@@@@|
|.......|
+-------+
Rock falls 1 unit:
|...@@@@|
+-------+
Jet of gas pushes rock left:
|..@@@@.|
+-------+
Rock falls 1 unit, causing it to come to rest:
|..####.|
+-------+
A new rock begins falling:
|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|.......|
|..####.|
+-------+
Jet of gas pushes rock left:
|..@....|
|.@@@...|
|..@....|
|.......|
|.......|
|.......|
|..####.|
+-------+
Rock falls 1 unit:
|..@....|
|.@@@...|
|..@....|
|.......|
|.......|
|..####.|
+-------+
Jet of gas pushes rock right:
|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|..####.|
+-------+
Rock falls 1 unit:
|...@...|
|..@@@..|
|...@...|
|.......|
|..####.|
+-------+
Jet of gas pushes rock left:
|..@....|
|.@@@...|
|..@....|
|.......|
|..####.|
+-------+
Rock falls 1 unit:
|..@....|
|.@@@...|
|..@....|
|..####.|
+-------+
Jet of gas pushes rock right:
|...@...|
|..@@@..|
|...@...|
|..####.|
+-------+
Rock falls 1 unit, causing it to come to rest:
|...#...|
|..###..|
|...#...|
|..####.|
+-------+
A new rock begins falling:
|....@..|
|....@..|
|..@@@..|
|.......|
|.......|
|.......|
|...#...|
|..###..|
|...#...|
|..####.|
+-------+
The moment each of the next few rocks begins falling, you would see this:
|..@....|
|..@....|
|..@....|
|..@....|
|.......|
|.......|
|.......|
|..#....|
|..#....|
|####...|
|..###..|
|...#...|
|..####.|
+-------+
|..@@...|
|..@@...|
|.......|
|.......|
|.......|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|..@@@@.|
|.......|
|.......|
|.......|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|...@...|
|..@@@..|
|...@...|
|.......|
|.......|
|.......|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|....@..|
|....@..|
|..@@@..|
|.......|
|.......|
|.......|
|..#....|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|..@....|
|..@....|
|..@....|
|..@....|
|.......|
|.......|
|.......|
|.....#.|
|.....#.|
|..####.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|..@@...|
|..@@...|
|.......|
|.......|
|.......|
|....#..|
|....#..|
|....##.|
|....##.|
|..####.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
|..@@@@.|
|.......|
|.......|
|.......|
|....#..|
|....#..|
|....##.|
|##..##.|
|######.|
|.###...|
|..#....|
|.####..|
|....##.|
|....##.|
|....#..|
|..#.#..|
|..#.#..|
|#####..|
|..###..|
|...#...|
|..####.|
+-------+
To prove to the elephants your simulation is accurate, they want to know how tall the tower will get after 2022 rocks have stopped (but before the 2023rd rock begins falling). In this example, the tower of rocks will be 3068 units tall.
How many units tall will the tower of rocks be after 2022 rocks have stopped falling?
Your puzzle answer was 3117.
--- Part Two ---
The elephants are not impressed by your simulation. They demand to know how tall the tower will be after 1000000000000 rocks have stopped! Only then will they feel confident enough to proceed through the cave.
In the example above, the tower would be 1514285714288 units tall!
How tall will the tower be after 1000000000000 rocks have stopped?
Your puzzle answer was 1553314121019.

1
17/input.txt Normal file

File diff suppressed because one or more lines are too long

1
17/sample-input.txt Normal file
View File

@ -0,0 +1 @@
>>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>

389
17/src/index.ts Normal file
View File

@ -0,0 +1,389 @@
import { readFileSync } from 'fs'
const Stream = {
left: 1,
right: -1,
} as const
const Space = {
rock: '#',
rock1: '&',
rock2: '@',
rock3: '*',
rock4: '$',
empty: '.',
} as const
const Shape = {
line: 'line',
J: 'J',
I: 'I',
square: 'square',
cross: 'cross',
} as const
type Streams = typeof Stream[keyof typeof Stream]
type Spaces = typeof Space[keyof typeof Space]
type Shapes = typeof Shape[keyof typeof Shape]
const Rocks: { [key: string]: Spaces[][] } = {
line: [['&', '&', '&', '&']],
cross: [
['.', '#', '.'],
['#', '#', '#'],
['.', '#', '.'],
],
J: [
['.', '.', '@'],
['.', '.', '@'],
['@', '@', '@'],
],
I: [['$'], ['$'], ['$'], ['$']],
square: [
['*', '*'],
['*', '*'],
],
}
type Block = {
shape: Spaces[][]
type: Shapes
row: number
column: number
width: number
height: number
}
type TowerFingerPrint = {
streamNumber: number
blockNumber: number
towerHeight: number
}
type Board = {
pit: Spaces[][]
width: number
height: number
fingerPrint: TowerFingerPrint[]
}
const Blocks: Block[] = [
{
shape: Rocks.line,
type: 'line',
row: 0,
column: 0,
width: Rocks.line[0].length,
height: Rocks.line.length,
},
{
shape: Rocks.cross,
type: 'cross',
row: 0,
column: 0,
width: Rocks.cross[0].length,
height: Rocks.cross.length,
},
{
shape: Rocks.J,
type: 'J',
row: 0,
column: 0,
width: Rocks.J[0].length,
height: Rocks.J.length,
},
{
shape: Rocks.I,
type: 'I',
row: 0,
column: 0,
width: Rocks.I[0].length,
height: Rocks.I.length,
},
{
shape: Rocks.square,
type: 'square',
row: 0,
column: 0,
width: Rocks.square[0].length,
height: Rocks.square.length,
},
]
function detectCycle(
board: Board,
blockNumber: number,
stream: Streams[],
streamNumber: number
): { blocks: number; streams: number; height: number } | null {
const currentTowerHeight = getTowerHeight(board)
const match = board.fingerPrint.find((fingerPrint) => {
return (
fingerPrint.streamNumber > stream.length &&
fingerPrint.streamNumber % stream.length === streamNumber % stream.length &&
fingerPrint.blockNumber % Blocks.length === blockNumber % Blocks.length &&
currentTowerHeight % fingerPrint.towerHeight === 0
)
})
const fingerPrint: TowerFingerPrint = {
streamNumber,
blockNumber,
towerHeight: getTowerHeight(board),
}
if (match) {
return {
blocks: fingerPrint.blockNumber - match.blockNumber,
streams: fingerPrint.streamNumber - match.streamNumber,
height: match.towerHeight,
}
} else {
board.fingerPrint.push(fingerPrint)
return null
}
}
function findLastIndex<T>(
array: T[],
predicate: (value: T, index: number, obj: T[]) => boolean
): number {
for (let i = array.length - 1; i >= 0; i--) {
if (predicate(array[i], i, array)) {
return i
}
}
return -1
}
function shiftLeft(board: Board, block: Block) {
if (canShiftLeft(board, block)) {
for (let i = 0; i < block.height; i++) {
for (let j = 0; j < block.width; j++) {
const pitRow = i + block.row
const pitColumn = j + block.column - 1
const blockSpace = block.shape[i][j]
if (blockSpace !== Space.empty) {
board.pit[pitRow][pitColumn] = blockSpace
board.pit[pitRow][pitColumn + 1] = Space.empty
}
}
}
block.column -= 1
}
}
function shiftRight(board: Board, block: Block) {
if (canShiftRight(board, block)) {
for (let i = 0; i < block.height; i++) {
for (let j = block.width - 1; j >= 0; j--) {
const pitRow = i + block.row
const pitColumn = j + block.column + 1
const blockSpace = block.shape[i][j]
if (blockSpace !== Space.empty) {
board.pit[pitRow][pitColumn] = blockSpace
board.pit[pitRow][pitColumn - 1] = Space.empty
}
}
}
block.column += 1
}
}
function shiftByStream(board: Board, direction: Streams, block: Block) {
if (direction === Stream.left) {
shiftLeft(board, block)
} else {
shiftRight(board, block)
}
// printBoard(board, `shift ${direction}`)
}
function shiftDown(board: Board, block: Block): boolean {
if (canShiftDown(board, block)) {
for (let i = block.height - 1; i >= 0; i--) {
for (let j = 0; j < block.width; j++) {
const pitRow = i + block.row + 1
const pitColumn = j + block.column
const blockSpace = block.shape[i][j]
if (blockSpace !== Space.empty) {
board.pit[pitRow][pitColumn] = blockSpace
board.pit[pitRow - 1][pitColumn] = Space.empty
}
}
}
block.row += 1
// printBoard(board, 'shifting down')
return true
} else {
// printBoard(board, 'could not shifting down')
return false
}
}
function canShiftDown(board: Board, block: Block): boolean {
for (let j = 0; j < block.width; j++) {
const lastBlockSpace = findLastIndex(
block.shape.map((row) => row[j]),
(space) => space !== Space.empty
)
const pitRow = board.pit[block.row + lastBlockSpace + 1]
const pitSpace = pitRow?.[block.column + j]
if (lastBlockSpace + block.row >= board.height || pitSpace !== Space.empty) {
return false
}
}
return true
}
function canShiftLeft(board: Board, block: Block): boolean {
for (let i = 0; i < block.height; i++) {
const pitRow = board.pit[block.row + i]
const firstBlockSpace = block.shape[i].findIndex((space) => space !== Space.empty)
const pitSpace = pitRow[block.column + firstBlockSpace - 1]
if (firstBlockSpace + block.column <= 0 || pitSpace !== Space.empty) {
return false
}
}
return true
}
function canShiftRight(board: Board, block: Block): boolean {
for (let i = 0; i < block.height; i++) {
const pitRow = board.pit[block.row + i]
const lastBlockSpace = findLastIndex(block.shape[i], (space) => space !== Space.empty)
const pitSpace = pitRow[block.column + lastBlockSpace + 1]
if (lastBlockSpace + block.column >= board.width || pitSpace !== Space.empty) {
return false
}
}
return true
}
function getTopBlockRow(board: Board): number {
const blockRow = board.pit.findIndex((row) => row.some((space) => space !== Space.empty))
return blockRow === -1 ? board.height : blockRow
}
function addBlock(board: Board, block: Block) {
const insertRowAbove = 3
const leftPlacement = 2
const additionalRows = insertRowAbove + block.height - getTopBlockRow(board)
if (additionalRows > 0) {
const newRows = Array(additionalRows)
.fill('')
.map(() => Array(board.width).fill(Space.empty))
board.pit.unshift(...newRows)
board.height += additionalRows
}
const insertRow = getTopBlockRow(board) - insertRowAbove - block.height
for (let i = 0; i < block.height; i++) {
for (let j = 0; j < block.width; j++) {
board.pit[i + insertRow][j + leftPlacement] = block.shape[i][j]
}
}
// printBoard(board, 'adding block')
block.row = insertRow
block.column = leftPlacement
}
function getNextBlock(blocks: Block[], blockNum: number): Block {
return { ...blocks[blockNum % blocks.length] }
}
function getNextStream(streams: Streams[], streamNum: number): Streams {
return streams[streamNum % streams.length]
}
function makeBoard(): Board {
const pit: Spaces[][] = Array(3)
.fill('.')
.map(() => Array(7).fill('.'))
return {
pit,
width: pit[0].length,
height: pit.length,
fingerPrint: [],
}
}
/*
function printBoard(board: Board, message = '') {
console.log(`\n${message}`)
console.log('\n+ +')
console.log(board.pit.map((row) => `|${row.join('')}|`).join('\n'))
console.log('+-------+\n')
}
*/
function getTowerHeight(board: Board): number {
return board.height - getTopBlockRow(board)
}
function playGame(stream: Streams[], blocks: Block[], times: number) {
const board = makeBoard()
let cycleHeight = 0
for (let i = 0, j = 0; i < times; i++) {
const block = getNextBlock(blocks, i)
addBlock(board, block)
shiftByStream(board, getNextStream(stream, j++), block)
while (shiftDown(board, block)) {
shiftByStream(board, getNextStream(stream, j++), block)
}
if (cycleHeight === 0) {
const cycle = detectCycle(board, i, stream, j - 1)
if (cycle) {
const blocksLeft = times - i
const cyclesLeft = Math.floor(blocksLeft / cycle.blocks)
i = i + cyclesLeft * cycle.blocks
j = j + cyclesLeft * cycle.streams
cycleHeight = cyclesLeft * cycle.height
}
}
}
return getTowerHeight(board) + cycleHeight
}
function parseSteam(lines: string[]): Streams[] {
const stream = lines.flatMap((line) =>
line.split('').map((char) => (char === '<' ? 1 : -1))
) as Streams[]
return stream
}
function solvePart1(lines: string[]): number {
const stream = parseSteam(lines)
return playGame(stream, Blocks, 2022)
}
function solvePart2(lines: string[]): number {
const stream = parseSteam(lines)
return playGame(stream, Blocks, 1000000000000)
}
function run() {
const input = process.argv.slice(2)[0]
const file = readFileSync(input, 'utf8')
const lines = file.split('\n').slice(0, -1)
const solution1 = solvePart1(lines)
console.log(`part1: ${solution1}`)
const solution2 = solvePart2(lines)
console.log(`part2: ${solution2}`)
}
run()