Skip to content

Instantly share code, notes, and snippets.

@pedromcunha
Created December 27, 2019 18:15
Show Gist options
  • Save pedromcunha/94a85369babf06bbfcbf263c231a176c to your computer and use it in GitHub Desktop.
Save pedromcunha/94a85369babf06bbfcbf263c231a176c to your computer and use it in GitHub Desktop.
AOC Part 3.2
class Plotter {
constructor() {
this.plots = {
wire1: {},
wire2: {},
intersects: {}
}
this.currentSteps = 0
}
plotWires(wire1, wire2) {
let position = {
x: 0,
y: 0
}
wire1.forEach((point) => this.plot(point, position, this.plots.wire1))
position = {
x: 0,
y: 0
}
this.currentSteps = 0
wire2.forEach((point) => this.plot(point, position, this.plots.wire2))
Object.keys(this.plots.wire1).forEach(plot => {
if (this.plots.wire2[plot] && plot != '0,0') {
let point = plot.split(",")
point = {
x: point[0],
y: point[1]
}
// const distance = Math.abs(point.x-0) + Math.abs(point.y-0);
if (!this.plots.intersects[this.plots.wire2[plot]]) {
this.plots.intersects[this.plots.wire2[plot]] = point
}
}
})
const min = Math.min.apply(null, Object.keys(this.plots.intersects).map((plot) => {
let point = this.plots.intersects[Number(plot)]
point = point.x + ',' + point.y
return this.plots.wire1[point] + this.plots.wire2[point]
}))
console.log('Combined minimum steps to first intersection:', min)
}
plot(point, position, points) {
const direction = point[0]
const value = Number(point.slice(1, point.length))
switch (direction) {
case "R":
for (var i = 0; i < value; i++) {
points[position.x + "," + position.y] = this.currentSteps
this.currentSteps++
position.x += 1
}
break
case "U":
for (var i = 0; i < value; i++) {
points[position.x + "," + position.y] = this.currentSteps
this.currentSteps++
position.y += 1
}
break
case "D":
for (var i = 0; i < value; i++) {
points[position.x + "," + position.y] = this.currentSteps
this.currentSteps++
position.y -= 1
}
break
case "L":
for (var i = 0; i < value; i++){
points[position.x + "," + position.y] = this.currentSteps
this.currentSteps++
position.x -= 1
}
break
}
}
}
const wirePlotter = new Plotter()
wirePlotter.plotWires(wire1, wire2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment