advent of code 2023 day 13: part II: vertical reflection

This commit is contained in:
Wouter Groeneveld 2023-12-13 17:33:21 +01:00
parent f93c50d3be
commit 0e4f6b8762
2 changed files with 35 additions and 30 deletions

View File

@ -1,27 +1,34 @@
const toPatternNotes = (pattern) => {
const isPerfectHorizontalReflection = (index) => {
let mirrored = true
let i = index - 1, j = index + 2
while(mirrored && i >= 0 && j < pattern.length) {
mirrored = pattern[i] === pattern[j]
i -= 1
j += 1
const toPatternNotes = (thePattern) => {
const findHorizontalMirror = (pattern, multiplier) => {
const isPerfectHorizontalReflection = (index) => {
let mirrored = true
let i = index - 1, j = index + 2
while(mirrored && i >= 0 && j < pattern.length) {
mirrored = pattern[i] === pattern[j]
i -= 1
j += 1
}
return mirrored
}
return mirrored
}
const findHorizontalMirror = () => {
for(let i = 1; i < pattern.length; i++) {
if(pattern[i - 1] === pattern[i] && isPerfectHorizontalReflection(i - 1)) {
return i * 100
return i * multiplier
}
}
return -1
}
const findVerticalMirror = () => {
const findVerticalMirror = (pattern, multiplier) => {
// 'Cheat' by finding the horizontal one by rotating 90 degrees
const matrix = pattern.map(line => line.split(''))
const rotated = matrix[0]
.map((val, index) => matrix.map(row => row[index]).reverse())
.map(arr => arr.join(''))
return findHorizontalMirror(rotated, multiplier)
}
return findHorizontalMirror()
const horizFound = findHorizontalMirror(thePattern, 100)
return horizFound != -1 ? horizFound : findVerticalMirror(thePattern, 1)
}
const solve = (input) => {
@ -33,4 +40,4 @@ const solve = (input) => {
module.exports = {
solve
}
}

View File

@ -4,6 +4,18 @@ const { readFileSync } = require('fs')
const { solve } = require('./impl.js')
test('The reflection notes for vertical reflection is the number of columns to its left', (t) => {
const input = `#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.`
assert.equal(5, solve(input))
})
test('The reflection notes for horizontal reflection is the number of rows above it multiplied by 100', (t) => {
const input = `#...##..#
#....#..#
@ -16,19 +28,6 @@ const input = `#...##..#
assert.equal(400, solve(input))
})
/*
test('The reflection notes for vertical reflection is the number of columns to its left', (t) => {
const input = `#.##..##.
..#.##.#.
##......#
##......#
..#.##.#.
..##..##.
#.#.##.#.`
assert.equal(5, solve(input))
})
test('The sum of the reflection notes in the assignment is 405', (t) => {
const input = `#.##..##.
..#.##.#.
@ -48,4 +47,3 @@ test('The sum of the reflection notes in the assignment is 405', (t) => {
assert.equal(405, solve(input))
})
*/