1_2.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { loadInput } from "../common.js";
  2. /** A dictionary to cache the counts of values from the right dictionary */
  3. const _countDictionary = {};
  4. // const input = loadInput("./1/test.input", parseInput, true);
  5. const input = loadInput(1, parseInput);
  6. solve(input);
  7. /**
  8. * @param {string} inputData
  9. * @returns {number[][]}
  10. */
  11. function parseInput(inputData) {
  12. // Split the input into lines, and then split each line into two numbers
  13. const lines = inputData.split(/\n/);
  14. let leftList = [];
  15. let rightList = [];
  16. // split each line into two numbers, then add those to the left and right lists
  17. for(const line of lines) {
  18. const [l, r] = line.split(/\s+/).map((num) => parseInt(num, 10));
  19. leftList.push(l);
  20. rightList.push(r);
  21. }
  22. return [leftList, rightList];
  23. }
  24. /**
  25. * @param {number[][]} parsedInput
  26. */
  27. function solve(parsedInput) {
  28. // separate out the already sorted left and right list
  29. const [leftList, rightList] = parsedInput;
  30. // Create a list to store the differences between the left and right list
  31. const similarityValues = [];
  32. for(const left of leftList) {
  33. similarityValues.push(left * countFromRightList(left, rightList));
  34. }
  35. console.log("List Distance: ", eval(similarityValues.join("+")));
  36. }
  37. /**
  38. * Get a count of the number of times a value appears in the right list
  39. *
  40. * @param {number} numberToFind The number to get a count of
  41. * @param {number[]} rightList The list to search through to get a count of {@link numberToFind}
  42. *
  43. * @returns {number} The number of times {@link numberToFind} appears in the right list
  44. */
  45. function countFromRightList(numberToFind, rightList) {
  46. if(_countDictionary[numberToFind]) {
  47. return _countDictionary[numberToFind];
  48. }
  49. const count = rightList.filter((value) => value == numberToFind).length;
  50. _countDictionary[numberToFind] = count;
  51. return count;
  52. }