re: AoC Day 5: Alchemical Reduction VIEW POST

VIEW FULL DISCUSSION
 

I went with RegExp solution. I created a regexp for all the reactions and delete everyting, then iterate until no more matches

const polymer = readFileSync('./data', {encoding: 'utf8'}).trim()

// A-Z
const upperLetters = [...Array(26)].map((_,i) => String.fromCharCode(65+i))

// A RegExp of the form Aa|...|Zz|aA|...|zZ
const regexp = new RegExp(
  upperLetters
    .map(upper => `${upper}${upper.toLocaleLowerCase()}`)
    .concat(upperLetters.map(upper => `${upper.toLocaleLowerCase()}${upper}`))
    .join("|"), "g")

// while there is a match for the regexp replace all and retry. returns the legnth
const reactToPolymer = polymerToReact => {
  while(regexp.test(polymerToReact)) {
    polymerToReact = polymerToReact.replace(regexp, "")
  }
  return polymerToReact.length
}

console.log(reactToPolymer(polymer))

Time: 0.265s

For part b y reuse all the code but add this

const reactions = upperLetters.map(letter => reactToPolymer(polymer.replace(new RegExp(letter, "gi"), "")))

console.log(Math.min(...reactions))

Time: 3.693s

I find the part b is a little slow using this approach

code of conduct - report abuse