To just solve:
Performance-wise, that means:
For criteria 1:
To solve optimally:
I think this will work. Only one way to find out.
Here's my code for identifying criteria 2 (difference of 1, 2, or 3):
let differFlag = true; let i = 1; while (differFlag && i < list.length) { let amount = Math.abs(list[i] - list[i - 1]); if (![1, 2, 3].includes(amount)) { differFlag = false; } i++; }
Here's my code for identifying criteria 1 (all differences increase or decrease):
let differFlag = true; let i = 1; let differences = []; while (differFlag && i < list.length) { let amount = list[i] - list[i - 1]; differences.push(amount); if (![1, 2, 3].includes(Math.abs(amount))) { differFlag = false; } i++; }
Here's the final condition that captures a safe report:
if ( differFlag && (differences.every((el) => el > 0) || differences.every((el) => el < 0)) ) { safeCount++; }
Altogether, my algorithm generates the correct answer for the example input.
Will it do the same for my puzzle input??
Yessssirrrreeee!!
Sweet!
This certainly complicates things a bit.
I'd like to avoid an algorithm that checks every possible permutation of a report. That would require generating millions of reports.
The first bit of good news is:
For my puzzle input, that's about 200 that don't require me to check permutations.
Still, 800/1000 is still a lot of lists to fully explore permutations.
I honestly don't see a way to avoid running my algorithm on each permutation of unsafe reports.
Bummer.
Time to add a loop to iterate through each number in unsafe reports - the number to remove and then check the mutated list for a passing grade.
I ended up duplicating my while loop with the added lines to duplicate and remove one number from each subsequent test report.
It's a lot more code.
But, it works! I generate the correct answer for the puzzle input!
Question is:
Let's run it and see...
Hmmm, it runs, but I get an answer that it only slightly greater than my Part 1 answer. That seems wrong.
Doesn't hurt to submit it, right????
It is correct!
Holy smokes!
That's incredible!
And really fun to solve!
Four gold stars going into Day 3.
Bring on more wonderful puzzles!
The above is the detailed content of Red-Nosed Reports. For more information, please follow other related articles on the PHP Chinese website!