repl.it
@Kognise/

AoC2019 3

Nodejs

Advent of Code is an Advent calendar of programming puzzles. https://adventofcode.com/2019/day/3

fork
loading
Files
  • index.js
  • input.txt
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const sum = (array) => array.reduce((a, c) => a + c, 0)
const reverseNumberSort = (a, b) => a > b ? 1 : -1

const getCoveredPoints = (wires) => {
  const points = {}
  const steps = {}

  for (let i = 0; i < wires.length; i++) {
    const currentPoint = [ 0, 0 ] // Vertical, horizontal
    let stepCounter = 0

    for (let instruction of wires[i]) {
      const amount = parseInt(instruction.slice(1))

      for (let j = 1; j <= amount; j++) {
        if (instruction[0] === 'U') {
          currentPoint[0]++
        } else if (instruction[0] === 'D') {
          currentPoint[0]--
        } else if (instruction[0] === 'R') {
          currentPoint[1]++
        } else if (instruction[0] === 'L') {
          currentPoint[1]--
        }
        stepCounter++

        const key = currentPoint.join(',')
        if (points[key]) {
          if (!points[key].includes(i)) {
            points[key].push(i)
            if (!steps[key][i]) steps[key][i] = stepCounter
          }
        } else {
          points[key] = [i]

          steps[key] = []
          steps[key][i] = stepCounter
        }
      }
    }
  }

  return { points, steps }
}

const getCrossoverKeys = (points) => {
  return Object.keys(points).reduce((acc, key) => {
    if (points[key].length > 1) acc.push(key)
    return acc
  }, [])
}

const wires = require('fs')
  .readFileSync('./input.txt')
  .toString()
  .split('\n')
  .map((line) => line.split(','))

const coveredPoints = getCoveredPoints(wires)
const crossoverKeys = getCrossoverKeys(coveredPoints.points)

const sortedDistances = crossoverKeys
  .map((key) => key.split(',').map((c) => parseInt(c)))
  .reduce((a, [ x, y ]) => {
    a.push(Math.abs(x) + Math.abs(y))
    return a
  }, [])
  .sort(reverseNumberSort)

console.log('Part one:', sortedDistances[0])

const sortedSteps = crossoverKeys
  .map((key) => coveredPoints.steps[key])
  .map((stepMap) => sum(stepMap))
  .sort(reverseNumberSort)

console.log('Part two:', sortedSteps[0])