Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created Dec 13, 2021
Embed
What would you like to do?
import { accessSync, promises as fs } from 'fs';
(async()=>{
const input = await fs.readFile("./interpretertests/aoc_21_13_input.txt", 'utf8')
const p = (grid) => {
for (let y = 0; y < grid.length; y++) {
console.log(grid[y].map(x=>x==0?'.':'#').join(''))
}
console.log('\n\n')
}
const fy = (grid, yf) => {
const nl = yf<grid.length/2?grid.length-yf-1:yf
let newGrid = Array.apply(null, Array(nl)).map(()=>Array.apply(null, Array(grid[0].length)).map(()=>0))
for (let y = 0; y < yf; y++) {
for (let x = 0; x < grid[y].length; x++) {
newGrid[y][x] = grid[y][x]
}
}
for (let y = yf+1; y < grid.length; y++) {
const yc = yf-(y-yf)
for (let x = 0; x < grid[y].length; x++) {
if (grid[y][x]) newGrid[yc][x] = grid[y][x]
}
}
return newGrid
}
const fx = (grid, xf) => {
const nl = xf<grid[0].length/2?grid[0].length-xf-1:xf
let newGrid = Array.apply(null, Array(grid.length)).map(()=>Array.apply(null, Array(nl)).map(()=>0))
for (let y = 0; y < grid.length; y++) {
for (let x = 0; x < xf; x++) {
newGrid[y][x] = grid[y][x]
}
}
for (let y = 0; y < grid.length; y++) {
for (let x = xf+1; x < grid[y].length; x++) {
const xc = xf-(x-xf)
if (grid[y][x]) newGrid[y][xc] = grid[y][x]
}
}
return newGrid
}
const cd = (grid) => {
return grid.reduce((acc, row)=>acc+row.reduce((acc, x)=>acc+x, 0), 0)
}
const mapping = input.split('\n').reduce((a,c)=>{
if (c.trim()=='') {
a.space = true
} else if (!a.space) {
const xy = c.trim().split(',').map(Number)
a.coords.push(xy)
if(xy[0]>a.max[0]) a.max[0] = xy[0]
if(xy[1]>a.max[1]) a.max[1] = xy[1]
} else {
const sp = c.trim().split('=')
a.folds.push([sp[0].endsWith('x'), parseInt(sp[1])])
}
return a
}, {coords: [], folds: [], space: false, max: [0,0]})
let grid = Array.apply(null, Array(mapping.max[1]+1)).map(()=>Array.apply(null, Array(mapping.max[0]+1)).map(()=>0))
for (let i=0; i<mapping.coords.length; i++) {
const xy = mapping.coords[i]
grid[xy[1]][xy[0]] = 1
}
console.log('#1', cd(fx(grid, mapping.folds[0][1])))
for (let f of mapping.folds) {
if (f[0]) {
grid = fx(grid, f[1])
} else {
grid = fy(grid, f[1])
}
}
console.log('#2')
p(grid)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment