Skip to content

Instantly share code, notes, and snippets.

@joeinnes
Created December 4, 2016 09:21
Show Gist options
  • Save joeinnes/a2c8224938afd60af85056a8bb3f6a70 to your computer and use it in GitHub Desktop.
Save joeinnes/a2c8224938afd60af85056a8bb3f6a70 to your computer and use it in GitHub Desktop.
Advent Of Code 2016 Day 1 created by joeinnes - https://repl.it/EfFK/24
const input = 'R3, L2, L2, R4, L1, R2, R3, R4, L2, R4, L2, L5, L1, R5, R2, R2, L1, R4, R1, L5, L3, R4, R3, R1, L1, L5, L4, L2, R5, L3, L4, R3, R1, L3, R1, L3, R3, L4, R2, R5, L190, R2, L3, R47, R4, L3, R78, L1, R3, R190, R4, L3, R4, R2, R5, R3, R4, R3, L1, L4, R3, L4, R1, L4, L5, R3, L3, L4, R1, R2, L4, L3, R3, R3, L2, L5, R1, L4, L1, R5, L5, R1, R5, L4, R2, L2, R1, L5, L4, R4, R4, R3, R2, R3, L1, R4, R5, L2, L5, L4, L1, R4, L4, R4, L4, R1, R5, L1, R1, L5, R5, R1, R1, L3, L1, R4, L1, L4, L4, L3, R1, R4, R1, R1, R2, L5, L2, R4, L1, R3, L5, L2, R5, L4, R5, L5, R3, R4, L3, L3, L2, R2, L5, L5, R3, R4, R3, R4, R3, R1'
const inputArray = input.split(', ')
function mover() {
this.xPos = 0
this.yPos = 0
this.heading = 0
this.visited = []
this.visitedTwice = []
this.turn = (direction) => {
if (direction === 'R') {
this.heading++
} else {
this.heading--
}
if (this.heading > 3) {
this.heading = 0
}
if (this.heading < 0) {
this.heading = 3
}
}
this.move = (distance) => {
switch(this.heading) {
case 0:
this.yPos += distance
break
case 1:
this.xPos += distance
break
case 2:
this.yPos -= distance
break
case 3:
this.xPos -= distance
break
}
}
this.hasBeenHereBefore = () => {
let returnValue = false
let locationString = `x${this.xPos}y${this.yPos}`
if (this.visited.indexOf(locationString) > -1) {
returnValue = true
}
this.visited.push(`x${this.xPos}y${this.yPos}`)
return returnValue
}
}
function part1 () {
let Santa = new mover()
inputArray.forEach((instruction) => {
let turnDirection = instruction[0]
let distance = parseInt(instruction.substring(1))
Santa.turn(turnDirection)
Santa.move(distance)
})
return Santa.xPos + Santa.yPos
}
function part2 () {
let SecondSanta = new mover()
inputArray.forEach((instruction) => {
let turnDirection = instruction[0]
let distance = parseInt(instruction.substring(1))
SecondSanta.turn(turnDirection)
while (distance) {
SecondSanta.move(1)
if (SecondSanta.hasBeenHereBefore()) {
SecondSanta.visitedTwice.push({x: SecondSanta.xPos, y: SecondSanta.yPos})
}
distance--
}
})
return SecondSanta.visitedTwice[0].x + SecondSanta.visitedTwice[0].y
}
console.log(`Part 1 Answer: Easter Bunny HQ is ${part1()} blocks away.`)
console.log(`Part 2 Answer: Easter Bunny HQ is really ${part2()} blocks away.`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment