Day 2 part 2

Let's get into it!

  1. I am going to do this the bruteforce way and check every possible skipping of values. This might be possible by checking if only one is causing the unsafe nature, but that seems complicated af.
  2. This time I have separated the safe-check into another function we can call multiple times:
  3. function is_safe(data_list){
      let ascending = (data_list[0] - data_list[1]) < 0;
      let last;
      for (let j of data_list) {
        if (last === undefined){
          last = j;
          continue;
        }
        if (Math.abs(last - j) > 3 || Math.abs(last - j) === 0 || (((last - j) < 0)) !== ascending) {
          return false;
        }
        last = j;
      }
      return true;
    }
  4. You can put this at the end of your js file. The only thing I changed aside from copying it is make it return a true/false value instead of adding one to the unsafe counter.
  5. Next we need to modify the main function:
    1. If the line is safe, great! We can continue to the next line.
    2. If not, we iterate through the possible skips. If one or more are safe, great! We can continue to the next line.
    3. If not, we add one to the unsafe counter.
        if (!is_safe(data_list)) {
          let unsafe_copies = 0;
          for (let j = 0; j < data_list.length; j++) {
            let one_ignored = data_list.filter((value, index) => index !== j);
            if (!is_safe(one_ignored)){
              unsafe_copies ++; // This one is the one indicating the number of unsafe permutations of this one line.
            }
          }
          if (unsafe_copies === data_list.length) {
            unsafe_num ++; // this one is the global
          }
        }
  6. I have only replaced the part I moved out to the separate "is_safe()" function, so we put this into the main for loop that remained, after the conversion to numbers.
  7. Now go submit this on the website and continue to the third day!


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




Output div