Im-doing-advent-of-code-day-one-using-javascript-can-someone-help-me-figure-out-how-to-write-a-function/

im-doing-advent-of-code-day-one-using-javascript-can-someone-help-me-figure-out-how-to-write-a-function/

the problem is I need to take two numbers in a pretty big array and figure out which two multiplied equals 2020. i will insert a link to where i input my code. i just do not know how to write out the right function. https://learn.grasshopper.app/gallery/edit?savedCode=iUHGKQczTMqjcRjFsKS0

Hi @HarpDev,

I often find that problems like this can best be solved by writing out the human steps we’d do if we were doing this manually, then turning that into code. It looks like the arrays you have in your link are the same array just copied to make your code easier but we don’t need to extrapolate that as we’re not altering the array in any way so we can read from the one array.

  • For every number in the array
  • Compare it to every number in the array
  • And output these numbers if they sum to our total (I know you said multiply but none of the numbers in your arrays will multiply to this, they’re too large, so I’ve changed it to sum)

In javascript (es6):


// "numbers" array not shown for brevity
let output = 2020;
numbers.forEach(number => {
    // ☝️ for every number in the array...
    numbers.forEach(number2 => {
        // ☝️ compare it to every number in the array...
        if (number + number2 === output) // use * instead of + if you really do want to check the product rather than the sum here!
        {
            // …and output these numbers if they sum to our total 👇
            console.log(`${number} + ${number2} = ${output}`); 
        }
    })
})

// outputs:
// > 1753 + 267 = 2020
// > 267 + 1753 = 2020

If you want to avoid es6 style code, you can do this using more traditional for loops, something like this should work but I couldn’t test it in that grasshopper tool as it has some looping restriction!

var output = 2020;

var number, number2; // not necessarily needed but might help readability later, could just do numbers[i] + numbers[j] etc.

for(var i = 0; i < numbers.length; i++)
{
    // ☝️ for every number in the array...
    number = numbers[i];

    for(var j = 0; j < numbers.length; j++)
    {
        // ☝️ compare it to every number in the array...
        number2 = numbers[j];
        
        if (number + number2 === output)
        {
            // …and output these numbers if they sum to our total 👇
            console.log(number + " + " + number2 + " = " + output);
        }
    }
}

I hope that helps your thinking about this and good luck in your coding! This stuff can be tricky to get right but it’s also great fun when you work these problems out.

The solutions above are only two of many possible solutions to this and are by far not the most efficient but for learning at this stage I think they’ll be helpful.

Cheers,
Billy :cowboy_hat_face: