2_1.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Safety check written this way to make troubleshooting easier
  39. for(let i = 0; i < report.length - 1; i++) {
  40. currDirection = numericAscSort(report[i], report[i + 1]);
  41. const difference = Math.abs(report[i] - report[i + 1]);
  42. // Check if the direction has changed, but skip the first round
  43. // Also catches if there were no differences between the two numbers
  44. if(i != 0 && lastDirection != currDirection) {
  45. safe = false;
  46. break;
  47. }
  48. // Make sure the difference wasn't too great
  49. else if(difference > 3) {
  50. safe = false;
  51. break;
  52. }
  53. else {
  54. safe = true;
  55. }
  56. lastDirection = currDirection;
  57. }
  58. if(safe) { safeReports++; }
  59. }
  60. // Not: ^400, ^391
  61. console.log("Safe Reports:", safeReports);
  62. }