DEV Community

Discussion on: AoC Day 1: Chronal Calibration

Collapse
 
herrfugbaum profile image
Pascal

1.1

A bit overcomplicated. Didn't know parseInt parses signs too 😅

const data = document.querySelector('pre').innerText

const frequencies = data.split('\n')

function getFrequency (freqs) {
  return freqs.reduce((acc, val) => {
    const sign = val[0] === '+' ? 1 : -1
    const number = val.substring(1)

    return acc + sign * number
  }, 0)
}

const result = getFrequency(frequencies)
console.log(result)

1.2

The first result is the solution, not quite sure why it prints so many other results after that even if I set matchFound = true though 🤔

const data = document.querySelector('pre').innerText

const frequencies = data.split('\n')
let sums = []

function getFrequency (freqs, acc=0, callback) {
  return freqs.reduce((acc, val) => {
    const sign = val[0] === '+' ? 1 : -1
    const number = val.substring(1)
    const current = acc + sign * number
    callback(current)
    return current
  }, acc)
}

let startFreq = getFrequency(frequencies, 0, current => sums.push(current))

function isMatch (arr, el) {
  return arr.find(element => element === el)
}

function findMatch () {
    let matchFound = false

    while(!matchFound) {
    startFreq = getFrequency(frequencies, startFreq, current => {
      if (isMatch(sums, current)) {
        matchFound = true
        console.log('The match is', current)
      }
    })
    }
}

findMatch()