DEV Community

Discussion on: AoC Day 2: Inventory Management System

Collapse
 
jnschrag profile image
Jacque Schrag

Giving it a go in good ol' JavaScript.

Part 1
First creates an Object to track the # of times a letter appears in a string. That gets converted to a Set to filter out any duplicate values to account for situations where 2 or more letters appeared twice (as the string only gets counted once for the check sum).

const input = text.split("\n").map(d => d.split(''))
let x2 = 0
let x3 = 0

input.forEach(line => {
  let counted = [...new Set(Object.values(line.reduce((allLetters, letter) => {
    if (letter in allLetters) {
      allLetters[letter]++
    } else {
      allLetters[letter] = 1
    }
    return allLetters
  }, {})))]
  x2 += counted.filter(d => d === 2).length
  x3 += counted.filter(d => d === 3).length
})

let checksum = x2 * x3

Part 2
I struggled with this one, so I'm sure there's a cleaner/more efficient way to do this. This takes each line of the input and compares it to the other lines, checking the characters and tracking the # of differences and the position of the last accounted for difference. The loops are set to break when a result with only 1 difference is found to prevent unnecessary looping.

const input = text.split("\n")

let check = true

for (let line of input) {
  const comparisonLines = input.filter(d => d !== line)

  for (let entry of comparisonLines) {
    let result = findDifferences(line, entry)
    if (result.numDiff === 1) {
      let string = line.slice(0, result.posDiff) + line.slice(result.posDiff + 1)
      console.log(string)
      check = false
      break
    }
  }
  if (!check) break
}

function findDifferences(string1, string2) {
  if (string1 === string2) return

  const length = Math.max(string1.length, string2.length)
  let numDiff = 0
  let posDiff = 0

  for (let i = 0; i <= length; i++) {
    if (string1[i] !== string2[i]) {
      numDiff++
      posDiff = i
    }
  }
  return {numDiff: numDiff, posDiff: posDiff}
}