Day 1 part 2

Let's continue with the second task!

  1. You will be using the same source file this time too, so you can continue in the same html + js files.
  2. Let's first collect the occurences of numbers in the first array.
  3.   const occurences = {};
      for (let i of col1){
        occurences[i] = occurences[i] ? occurences[i] + 1 : 1;
      }
      document.getElementById("output").innerHTML += JSON.stringify(occurences);
  4. The ?: operator is quite a useful function, it checks the expression written before the question mark, if true, executes the part before the colon, if false, it executes the part after.
  5. Here we check for the existence of a number in our object (which you might know as a dictionary from other languages, but it is also what arrays, classes and other stuff inherit), and if it exists we add one, if not we set it to 1.
  6. "JSON.stringify()" takes a javascript object and makes it into a simple string we can read.
  7. Now we need to sum up the numbers based on this object's content, and let's print the result out while we're at it.
  8.   let sim_score = 0;
      for (let j of col2){
        sim_score += occurences[j]? occurences[j]*j: 0;
      }
      document.getElementById("output").innerHTML += sim_score;
  9. This time we go through the second list and add the number multiplied with the occurrences of it in the other list.
  10. We do need to check the existence of the number this time too as undefined + 1 is NaN.
  11. Now with that you should have gotten the correct sum printed out.
  12. Submit this one too on the advent of code website.

Continue to the next day


If you want a response, please include a reply address (email, Discord, etc.).




Output div