DEV Community

Discussion on: AoC Day 8: Memory Maneuver

Collapse
themindfuldev profile image
Tiago Romero Garcia • Edited on

JavaScript solution

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
};

08-common.js

class Node {
    constructor(childNodesSize, metadataEntriesSize) {
        this.childNodesSize = +childNodesSize;
        this.metadataEntriesSize = +metadataEntriesSize;
        this.childNodes = [];
        this.metadataEntries = [];
    }
}

const buildNode = (input, i = 0) => {
    const node = new Node(input[i], input[i + 1]);
    i += 2;

    for (let j = 0; j < node.childNodesSize; j++) {
        let [children, newI] = buildNode(input, i);
        i = newI;
        node.childNodes.push(children);
    }    

    node.metadataEntries.push(...input.slice(i, i + node.metadataEntriesSize).map(entry => +entry));
    i += node.metadataEntriesSize;
    return [node, i];
};

const buildTree = input => {
    const [root, i] = buildNode(input);
    return root;
};

module.exports = {
    Node,
    buildNode,
    buildTree
};

08a.js

const { readFile } = require('./reader');
const { buildTree } = require('./08-common');

const sumMetadata = root => {
    let total = 0;
    let queue = [root];
    while (queue.length > 0) {
        const node = queue.shift();
        total += node.metadataEntries.reduce((sum, entry) => sum + entry, 0);
        queue.push(...node.childNodes);
    }
    return total;
};

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

    const tree = buildTree(lines[0].split(' '));

    const sum = sumMetadata(tree);

    console.log(`The sum of all metadata entries is ${sum}`);
})();

08b.js

const { readFile } = require('./reader');
const { buildTree } = require('./08-common');

const getNodeValue = node => {
    let value = 0;
    if (node.childNodesSize === 0) {
        value += node.metadataEntries.reduce((sum, entry) => sum + entry, 0);
    }
    else {
        for (let entry of node.metadataEntries) {
            const child = node.childNodes[entry-1];
            if (child) {
                value += getNodeValue(child);
            }
        }
    }
    return value;
}

const getRootNodeValue = root => {
    return getNodeValue(root);
};

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

    const tree = buildTree(lines[0].split(' '));

    const rootNodeValue = getRootNodeValue(tree);

    console.log(`The value of the root node is is ${rootNodeValue}`);
})();