day 06 part 1 finished
This commit is contained in:
73
2024/06/index.js
Normal file
73
2024/06/index.js
Normal file
@ -0,0 +1,73 @@
|
||||
import fs from 'node:fs'
|
||||
|
||||
let map = []
|
||||
function init(filename) {
|
||||
const data = fs.readFileSync(filename, { encoding: 'utf-8' }, data => data)
|
||||
map = data.split('\n')
|
||||
const guard = new Guard()
|
||||
guard.position = guard.find()
|
||||
|
||||
console.log(`guard is at ${guard.position}`)
|
||||
guard.solve1()
|
||||
}
|
||||
|
||||
class Guard {
|
||||
constructor() {
|
||||
this.position = [0, 0]
|
||||
this.visited = []
|
||||
this.dir = [-1, 0] // y, x - looking up
|
||||
this.steps = 0
|
||||
}
|
||||
rotate() {
|
||||
const [y, x] = this.dir
|
||||
if (y === -1 && x === 0) { console.log(`going right`); this.dir = [0, 1] }
|
||||
if (y === 0 && x === 1) { console.log(`going down`); this.dir = [1, 0] }
|
||||
if (y === 1 && x === 0) { console.log(`going left`); this.dir = [0, -1] }
|
||||
if (y === 0 && x === -1) { console.log(`going up`); this.dir = [-1, 0] }
|
||||
return this.dir
|
||||
}
|
||||
find() {
|
||||
for (let y = 0; y < map.length; y++) {
|
||||
for (let x = 0; x < map[y].length; x++) {
|
||||
if (map[y][x] === "^") return [y, x]
|
||||
}
|
||||
}
|
||||
}
|
||||
goStraight() {
|
||||
const [y, x] = this.position
|
||||
const [dy, dx] = this.dir
|
||||
this.position = [y + dy, x + dx]
|
||||
//const iWasAlreadyHere = this.visited.some(visits => visits.split()[0] === y + dy && visits.split()[1] === x + dx)
|
||||
if (!this.visited.includes(this.position)) this.visited.push(this.position)
|
||||
|
||||
this.steps += 1
|
||||
|
||||
}
|
||||
isLeaving() {
|
||||
const [y, x] = this.position
|
||||
const [dy, dx] = this.dir
|
||||
return x + dx < 0 || x + dx > map[0].length || y + dy < 0 || y + dy >= map.length
|
||||
}
|
||||
isBlockAhead() {
|
||||
const [y, x] = this.position
|
||||
const [dy, dx] = this.dir
|
||||
return map[y + dy][x + dx] === "#" ? true : false
|
||||
}
|
||||
isStillOnMap() {
|
||||
const [y, x] = this.position
|
||||
return (y >= 0 && y <= map.length) && (x >= 0 && x <= map[0].length)
|
||||
}
|
||||
solve1() {
|
||||
console.log("y", map.length, "x", map[0].length)
|
||||
this.visited = [this.position]
|
||||
while (this.isStillOnMap()) {
|
||||
if (this.isLeaving()) { console.log(`ran ${this.steps} steps`); break }
|
||||
if (this.isBlockAhead()) this.rotate()
|
||||
this.goStraight(this.dir)
|
||||
}
|
||||
this.visited = Array.from(new Set(this.visited.map(JSON.stringify)), JSON.parse);
|
||||
console.log(this.visited.length)
|
||||
}
|
||||
}
|
||||
|
||||
init('input.txt')
|
Reference in New Issue
Block a user