Advent of Code, Day 3: Toboggan Trajectory
Go to Day 3 Challenge |
Go to index
I ran this code in the devtoolbar in Chrome, and the answers were simply outputted to the console.
Learn more about my solution.
Part I
"You start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map).
The toboggan can only follow a few specific slopes (you opted for a cheaper model that prefers rational numbers); start by counting
all the trees you would encounter for the slope right 3, down 1."
ref
var nums = window.document.getElementsByTagName("pre")[0]
nums = nums.innerText.split('\n')
var columnCounter = 0
var treeCounter = 0
nums.forEach((row, index) => {
var fullRow = row.repeat(40)
if(fullRow.substring(columnCounter,columnCounter+1) === '#') {
console.error('tree hit row:', index, 'column:', columnCounter)
treeCounter++
}
columnCounter += 3
})
console.warn('total trees', treeCounter)
Part II
"Time to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all."
ref
var nums = window.document.getElementsByTagName("pre")[0]
nums = nums.innerText.split('\n')
var slopes = [{ right: 1, down: 1 },{ right: 3, down: 1 },{ right: 5, down: 1 },{ right: 7, down: 1 },{ right: 1, down: 2}]
var total = 1
slopes.forEach(slope => {
var columnCounter = 0
var treeCounter = 0
nums.forEach((row, index) => {
if(index % slope.down === 0) {
var fullRow = row.repeat(100)
if(fullRow.substring(columnCounter,columnCounter+1) === '#') {
treeCounter++
}
columnCounter += slope.right
}
})
console.warn('total trees for', slope.right, 'x', slope.down, 'is', treeCounter)
total *= treeCounter
})
console.warn('total trees', total)