DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 15: Rambunctious Recitation

Collapse
 
kudostoy0u profile image
Kudos Beluga • Edited

Here's part 1 JS, part 2 is a big performance issue. EDIT: I tried using new Map() for a more efficient process but I still ran into the call stack size error. I guess Javascript and heavy processing don't fit together :(

const fs = require("fs")
let arr = fs.readFileSync("input.txt", "utf8").split(",").map(e => Number(e)),
    len = arr.length;
const getnextnumber = (counter = 0) => {
    if (counter == (2020 - len)) console.log(arr[arr.length - 1])
    else {
        let index = arr.slice(arr, arr.length - 1).lastIndexOf(arr[arr.length - 1]);
        if (index > -1) {
            arr.push(arr.length - index - 1)
            getnextnumber(counter + 1)
        } else {
            arr.push(0)
            getnextnumber(counter + 1)
        }
    }
}
getnextnumber()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shalvah profile image
Shalvah

You can use a map to store the numbers you've seen. Map lookup is O(1), compared to looking through a list (O(n)). The keys can be the numbers you've seen, the values the list of positions.

Collapse
 
kudostoy0u profile image
Kudos Beluga

Thank you for the suggestion! I'll try it!