-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay1.js
More file actions
35 lines (32 loc) · 1.27 KB
/
Day1.js
File metadata and controls
35 lines (32 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { readFileSync } from 'node:fs';
import * as math from 'mathjs';
// Reading in the input file
const inputFile = readFileSync('../../AdventOfCode_inputs/day1_input.txt')
const fileSplit = inputFile.toString().split('\n')
// Sort file into left and right column lists
var leftColumn = [];
var rightColumn = [];
fileSplit.forEach(line => {
leftColumn.push(Number(line.split(/\s+/)[0]));
rightColumn.push(Number(line.split(/\s+/)[1]));
})
function sortDistance(leftColumn, rightColumn) {
// First sort the two columns from smallest to largest
// then calculate and sum the distances between the two columns
leftColumn.sort();
rightColumn.sort();
const negRightColumn = rightColumn.map(x => -x);
const difference = math.add(leftColumn, negRightColumn);
return math.sum(math.abs(difference));
}
function similarityScore(leftColumn, rightColumn) {
var similarity = 0;
leftColumn.forEach(element => {
// Count how many times the element from leftColumn appears in rightColumn
var amount = rightColumn.filter((currentItem) => currentItem == element).length;
similarity += element * amount;
})
return similarity;
}
console.log(sortDistance(leftColumn, rightColumn));
console.log(similarityScore(leftColumn, rightColumn));