2

I am working through day 7 of the Advent of Code and am stuck on why my code is returning undefined when the base case in findNestedBags hits the first condition (data[key].includes(color)). It returns 0 when the second case is true so I am confused why one works and the other doesn't.

The objective is to figure out how many different bags will lead to a bag that contains a 'shiny gold' bag. If a certain colored bag contains a shiny gold bag as an option (found in the value of key/value pair), it's an option. Alternatively, if one of the bags in list then has shiny gold as an option in its key/value pair, that can count as well...

This is a sample of the data structure as found in the variable data, just with many more rows:


data = {
  'vibrant violet': [ 'light gray', 'wavy aqua' ],
  'dim fuchsia': [ 'vibrant white', 'pale beige', 'shiny gold' ],
  'drab fuchsia': [ 'dotted turquoise', 'dull crimson', 'plaid violet' ],
  'dim purple': [ 'plaid silver', 'posh gray', 'plaid beige' ],
  'mirrored lavender': [ 'vibrant lime', 'vibrant violet', 'mirrored aqua', 'clear black' ],
  'posh green': []
}
let data = indexData(input);

let count = 0;
function findMatches(color, input) {
    for (let key in input) {
        
        if (input[key].includes(color)) {
            count++
        }
        else {
            let x = findNestedBags(key, color, input)
            if (x == 1) count++
        }
    }
    return count
}

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    }

    else if (data[key].length == 0) {
        return 0;
    }
    else {
        data[key].forEach(item => {
            return findNestedBags(item, color, data)
        })
    }

}

1 Answer 1

2

forEach does not return a value. If you want to sum all the results, you can use Array#reduce. In addition, you can set the accumulator's initial value to 0 by passing in a second argument, so you can remove the check for the array's length being 0.

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    } else {
        return data[key].reduce((acc,item) => {
            return acc + findNestedBags(item, color, data)
        }, 0)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

…and if it is an array, you don't need to test for length == 0 first either

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.