DEV Community

Discussion on: AoC Day 5: Alchemical Reduction

Collapse
 
themindfuldev profile image
Tiago Romero Garcia • Edited

JavaScript solution

For this solution I used a stack. If the unit on top of the stack can react to the incoming unit, I just pop it out of the stack. Otherwise, I push it and move on.

reader.js

const fs = require('fs');
const readline = require('readline');

const readLines = (file, onLine) => {
    const reader = readline.createInterface({
        input: fs.createReadStream(file),
        crlfDelay: Infinity
    });

    reader.on('line', onLine);

    return new Promise(resolve => reader.on('close', resolve));
};

const readFile = async file => {
    const lines = [];
    await readLines(file, line => lines.push(line));  
    return lines;
}

module.exports = {
    readLines,
    readFile
};

05-common.js

const reactPolymer = polymer => {
    let stack = [];
    for (let char of polymer.split('')) {
        const top = stack[stack.length - 1];
        if (top && top.toLowerCase() === char.toLowerCase() && top !== char) {
            stack.pop();
        }
        else {
            stack.push(char);
        }
    }

    return stack;
}

module.exports = {
    reactPolymer
};

05a.js

const { readFile } = require('./reader');
const { reactPolymer } = require('./05-common');

(async () => {
    const lines = await readFile('05-input.txt');

    const polymer = reactPolymer(lines[0]);

    console.log(`The remaining units are ${polymer.length}`);
})();

05b.js

const { readFile } = require('./reader');
const { reactPolymer } = require('./05-common');

const detectUnitTypes = polymer => {
    const existence = new Set();
    return polymer.toLowerCase().split('').filter(unit => {
        if (existence.has(unit)) {
            return false;
        }
        existence.add(unit);
        return true;
    });
};

(async () => {
    const lines = await readFile('05-input.txt');

    const unitTypes = detectUnitTypes(lines[0]);

    const polymersWithoutUnit = new Map();
    for (let unit of unitTypes) {
        const polymer = reactPolymer(lines[0].replace(new RegExp(unit, 'ig'), ''));
        polymersWithoutUnit.set(unit, polymer.length);
    }

    const shortestPolymerLength = Math.min(...polymersWithoutUnit.values());

    console.log(`The shortest polymer length is ${shortestPolymerLength}`);
})();