DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 9: Encoding Error

Collapse
 
kudostoy0u profile image
Kudos Beluga • Edited

Here's my js solution,toggle part2 to true or false depending on your needs :

const fs = require("fs"),
    part2 = false;
fs.readFile("input.txt", "utf8", (err, data) => {
    if (err) throw err;
    let d = data.split("\n").map(e => Number(e));
    for (let i = 25; i < d.length; i++) {
        let first25 = d.slice(i - 25, i),
            matched;
        for (j in first25) {
            for (k in first25) {
                if ((first25[j] != first25[k]) && ((first25[k] + first25[j]) == d[i])) matched = true;
            }
        }
        if (!matched && !part2) console.log(d[i]);
        else if (!matched && part2) {
            for (let j = 0; j < d.length; j++) {
                for (let l = 0; l < d.length; l++) {
                    let arr = [];
                    for (let k = l; k < j + l; k++) {
                        arr.push(d[k]);
                    }
                    arr = arr.filter(e => e);
                    if (arr.length > 1) {
                        if (arr.reduce((total, num) => total + num) == d[i]) console.log(Math.min(...arr) + Math.max(...arr));
                    }
                }
            }
        }
    }
})
Enter fullscreen mode Exit fullscreen mode


)