Skip to content

Instantly share code, notes, and snippets.

@Mellen
Created December 13, 2021 10:01
Show Gist options
  • Save Mellen/c40d56ca2285345355636061eef86c9f to your computer and use it in GitHub Desktop.
Save Mellen/c40d56ca2285345355636061eef86c9f to your computer and use it in GitHub Desktop.
(function(inp)
{
function draw(points, maxX, maxY)
{
let str = '';
for(let y = 0; y <= maxY; y++)
{
for(let x = 0; x <= maxX; x++)
{
let p = `${x},${y}`;
if(points.has(p))
{
str += '#';
}
else
{
str += '.'
}
}
str += '\n';
}
return str;
}
function fold(points, maxX, maxY, axis, foldCoord)
{
let newPoints = new Set();
let pindex = axis=='x'?0:1;
let bottom = axis=='x'?maxX:maxY;
for(let point of points)
{
let coord = point.split(',');
let val = parseInt(coord[pindex],10);
if(val != foldCoord)
{
if(val < foldCoord)
{
newPoints.add(point);
}
else
{
val = bottom - val;
coord[pindex] = val;
newPoints.add(coord.join(','));
}
}
}
return newPoints;
}
let points = new Set();
let [pstr, fstr] = inp.split('\n\n');
let parr = pstr.split('\n');
let maxX = 0;
let maxY = 0;
for(let p of parr)
{
let [x,y] = p.split(',');
x = parseInt(x,10);
y = parseInt(y,10);
if(x > maxX)
{
maxX = x;
}
if(y > maxY)
{
maxY = y;
}
points.add(p)
}
fstr = fstr.trim();
let foldLines = fstr.split('\n');
for(let fl of foldLines)
{
let [rest, fcstr] = fl.split('=');
let foldCoord = parseInt(fcstr,10);
let axis = rest[rest.length-1];
points = fold(points, maxX, maxY, axis, foldCoord);
if(axis == 'y')
{
maxY = foldCoord - 1;
}
else
{
maxX = foldCoord - 1;
}
}
return draw(points, maxX, maxY);
})(document.querySelector('pre').textContent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment