1_1.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { loadInput, numericAscSort } from "../common.js";
  2. const input = loadInput(1, parseInput);
  3. solve(input);
  4. /**
  5. * @param {string} inputData
  6. * @returns {number[][]}
  7. */
  8. function parseInput(inputData) {
  9. // Split the input into lines, and then split each line into two numbers
  10. const lines = inputData.split(/\n/);
  11. let leftList = [];
  12. let rightList = [];
  13. // split each line into two numbers, then add those to the left and right lists
  14. for(const line of lines) {
  15. const [l, r] = line.split(/\s+/).map((num) => parseInt(num, 10));
  16. leftList.push(l);
  17. rightList.push(r);
  18. }
  19. leftList.sort(numericAscSort);
  20. rightList.sort(numericAscSort);
  21. return [leftList, rightList];
  22. }
  23. /**
  24. * @param {number[][]} parsedInput
  25. */
  26. function solve(parsedInput) {
  27. // separate out the already sorted left and right list
  28. const [leftList, rightList] = parsedInput;
  29. // Create a list to store the differences between the left and right list
  30. const deltaList = [];
  31. while(leftList.length) {
  32. deltaList.push(Math.abs(rightList.shift() - leftList.shift()));
  33. }
  34. console.log("List Distance: ", eval(deltaList.join("+")));
  35. }