re: AoC Day 5: Alchemical Reduction VIEW POST


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(
    .map(upper => `${upper}${upper.toLocaleLowerCase()}`)
    .concat( => `${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


Time: 0.265s

For part b y reuse all the code but add this

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


Time: 3.693s

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

code of conduct - report abuse