2_2.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { loadInput, numericAscSort, strToInt } from "../common.js";
  2. // const input = loadInput("./2/test.input", parseInput, true);
  3. const input = loadInput(2, parseInput);
  4. solve(input);
  5. /**
  6. * @param {string} inputData
  7. * @returns {number[]}
  8. */
  9. function parseInput(inputData) {
  10. const reports = inputData.split(/\n/).map((report) => report.split(" ").map(strToInt));
  11. return reports;
  12. }
  13. /**
  14. * @param {number[]} parsedInput
  15. */
  16. function solve(parsedInput) {
  17. let safeReports = 0;
  18. for(const report of parsedInput) {
  19. let currDirection = 0;
  20. let lastDirection = 0;
  21. /**
  22. * Whether or not the report is safe
  23. *
  24. * Report is only safe when the data is sorted in one direction, and
  25. * each value is no less than 1 value away, and no more than 3 values
  26. * away from each other.
  27. *
  28. * e.g.
  29. * ```
  30. * 1,2,3,4,5 safe
  31. * 5,4,3,2,1 safe
  32. * 1,2,3,2,1 unsafe
  33. * 1,2,4,5,6 safe
  34. * 1,2,7,8,9 unsafe
  35. * ```
  36. */
  37. let safe = false;
  38. /**
  39. * The Problem Dampener allows one failed safety meassure
  40. */
  41. let problemDampenerActive = true;
  42. // Safety check written this way to make troubleshooting easier
  43. for(let i = 0; i < report.length - 1; i++) {
  44. currDirection = numericAscSort(report[i], report[i + 1]);
  45. const difference = Math.abs(report[i] - report[i + 1]);
  46. // Check if the direction has changed, but skip the first round
  47. // Also catches if there were no differences between the two numbers
  48. if(i != 0 && lastDirection != currDirection) {
  49. if (problemDampenerActive) {
  50. problemDampenerActive = false;
  51. }
  52. else {
  53. safe = false;
  54. break;
  55. }
  56. }
  57. // Make sure the difference wasn't too great
  58. else if(difference > 3) {
  59. if (problemDampenerActive) {
  60. problemDampenerActive = false;
  61. }
  62. else {
  63. safe = false;
  64. break;
  65. }
  66. }
  67. else {
  68. safe = true;
  69. }
  70. lastDirection = currDirection;
  71. }
  72. if(safe) { safeReports++; }
  73. }
  74. // Not: ^400, ^391
  75. console.log("Safe Reports:", safeReports);
  76. }