1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import { loadInput } from "../common.js";
- /** A dictionary to cache the counts of values from the right dictionary */
- const _countDictionary = {};
- // const input = loadInput("./1/test.input", parseInput, true);
- const input = loadInput(1, parseInput);
- solve(input);
- /**
- * @param {string} inputData
- * @returns {number[][]}
- */
- function parseInput(inputData) {
- // Split the input into lines, and then split each line into two numbers
- const lines = inputData.split(/\n/);
- let leftList = [];
- let rightList = [];
- // split each line into two numbers, then add those to the left and right lists
- for(const line of lines) {
- const [l, r] = line.split(/\s+/).map((num) => parseInt(num, 10));
- leftList.push(l);
- rightList.push(r);
- }
- return [leftList, rightList];
- }
- /**
- * @param {number[][]} parsedInput
- */
- function solve(parsedInput) {
- // separate out the already sorted left and right list
- const [leftList, rightList] = parsedInput;
- // Create a list to store the differences between the left and right list
- const similarityValues = [];
- for(const left of leftList) {
- similarityValues.push(left * countFromRightList(left, rightList));
- }
- console.log("List Distance: ", eval(similarityValues.join("+")));
- }
- /**
- * Get a count of the number of times a value appears in the right list
- *
- * @param {number} numberToFind The number to get a count of
- * @param {number[]} rightList The list to search through to get a count of {@link numberToFind}
- *
- * @returns {number} The number of times {@link numberToFind} appears in the right list
- */
- function countFromRightList(numberToFind, rightList) {
- if(_countDictionary[numberToFind]) {
- return _countDictionary[numberToFind];
- }
- const count = rightList.filter((value) => value == numberToFind).length;
- _countDictionary[numberToFind] = count;
- return count;
- }
|