AOC Solutions

For a description of this problem, please check the Advent of Code website.

Example Input:

MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX

Part 1 Solution:

const fs = require('fs');
const data = fs.readFileSync('./input.txt', 'utf8');
const grid = data.trim().split('\n');
const gridHeight = grid.length
const gridWidth = grid[0].length
const directions = [
{ x: 0, y: -1 },
{ x: 1, y: -1 },
{ x: 1, y: 0 },
{ x: 1, y: 1 },
{ x: 0, y: 1 },
{ x: -1, y: 1 },
{ x: -1, y: 0 },
{ x: -1, y: -1 }
]
let matches = 0;
for(y=0; y < gridHeight; y++) {
for (x=0; x < gridWidth; x++) {
if (grid[y][x] !== 'X') continue;
matches += directions.reduce((sum, direction) => {
let word = 'X';
let curX = x, curY = y;
for(i=0; i<3; i++) {
curX += direction.x
curY += direction.y
if (!(curX < 0 || curX >= gridWidth || curY < 0 || curY >= gridHeight)) {
word += grid[curY][curX]
}
}
return sum + (word === 'XMAS' ? 1 : 0);
}, 0)
}
}
console.log(matches)

Part 2 Solution:

const fs = require('fs');
const data = fs.readFileSync('./input.txt', 'utf8');
const grid = data.trim().split('\n');
const gridHeight = grid.length
const gridWidth = grid[0].length
let matches = 0;
function getChar(x, y) {
if (!(x < 0 || x >= gridWidth || y < 0 || y >= gridHeight)) {
return grid[y][x];
}
}
for(y=0; y < gridHeight; y++) {
for (x=0; x < gridWidth; x++) {
if (grid[y][x] !== 'A') continue;
const word1 = getChar(x - 1, y + 1) + 'A' + getChar(x + 1, y - 1);
const word2 = getChar(x + 1, y + 1 ) + 'A' + getChar(x - 1, y - 1);
if ((word1 === 'MAS' || word1 === 'SAM') && (word2 === 'MAS' || word2 === 'SAM')) matches++;
}
}
console.log(matches)