All files / day4 puzzle1.js

100% Statements 24/24
100% Branches 4/4
100% Functions 5/5
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 481x 1x   1x 204x 204x   204x 204x   204x           1x 204x   204x 4981x 849x 165x   684x         204x     1x 2x 2x 2x 202x 202x   2x     1x          
const { readFile } = require('../helpers/file')
const { convertStringWithNumbersToArray } = require('../helpers/strings')
 
const extractWiningCombinaisonAndProposals = (str) => {
  let sections = str.split(/[:|]/)
  sections.shift()
 
  let numbers = sections[0].match(/\d+/g)
  let winningNumbers = sections[1].match(/\d+/g)
 
  return [
    convertStringWithNumbersToArray(numbers),
    convertStringWithNumbersToArray(winningNumbers),
  ]
}
 
const countPoints = (winningNb, proposals) => {
  let pts = 0
 
  proposals.forEach((number) => {
    if (winningNb.includes(number)) {
      if (pts === 0) {
        pts++
      } else {
        pts = 2 * pts
      }
    }
  })
 
  return pts
}
 
const resolvePuzzle = (input) => {
  const data = readFile(input)
  let sum = 0
  data.forEach((line, index) => {
    const [winningNb, proposals] = extractWiningCombinaisonAndProposals(line)
    sum += countPoints(winningNb, proposals)
  })
  return sum
}
 
module.exports = {
  resolvePuzzle,
  extractWiningCombinaisonAndProposals,
  countPoints,
}