Skip to content

Commit 9399d3b

Browse files
authored
Merge pull request #2 from avolutions/day-1
Day 1
2 parents 40eb148 + e3d7686 commit 9399d3b

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ My solutions for [Advent of Code 2024](https://adventofcode.com/) written in Typ
99
> npm install
1010
3. Build:
1111
> npm run build
12-
12+
1313
# Usage
1414
The solutions to the puzzles for each day can be selected and executed separately.
1515

@@ -34,3 +34,4 @@ After executing the solution, either by selecting it from the list or by calling
3434
# Solutions
3535
Day | Command | Part 1 | Part 2
3636
--- | --- | --- | ---
37+
[Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1) | `npm run advent 1` | [57fb22f](https://github.com/avolutions/adventofcode/commit/57fb22ff139de656c4bbea2c93026f88a4732ad2) | [f51986c](https://github.com/avolutions/adventofcode/commit/f51986c200f3ee12aaa65e7487fe87a1291f4635)

src/day-1/index.ts

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import { readFileFromCurrentDirectory } from '../utils/readFile.js';
2+
3+
const content = readFileFromCurrentDirectory();
4+
5+
const leftValues: number[] = [];
6+
const rightValues: number[] = [];
7+
8+
// Split the content into lines
9+
const lines = content.trim().split("\n");
10+
11+
// Process each line and split into columns
12+
lines.forEach(line => {
13+
const [left, right] = line
14+
.trim()
15+
.split(/\s+/)
16+
.map(Number); // Split by spaces or tabs and convert to numbers
17+
18+
leftValues.push(left);
19+
rightValues.push(right);
20+
});
21+
22+
// Sort arrays in ascending order
23+
leftValues.sort((a, b) => a - b);
24+
rightValues.sort((a, b) => a - b);
25+
26+
// Calculate distance between the values
27+
const distance = leftValues.reduce((sum, left, index) => {
28+
return sum + Math.abs(left - rightValues[index]);
29+
}, 0);
30+
31+
console.log("Part 1: " + distance);
32+
33+
// Calculate similarity score
34+
let similarityScore = 0;
35+
36+
for (const leftValue of leftValues) {
37+
// Count how many times the left value appears in right list
38+
const appearanceInRight = rightValues.filter(rightValue => rightValue === leftValue).length;
39+
40+
// Calculate similarity score
41+
similarityScore += (leftValue * appearanceInRight);
42+
}
43+
44+
console.log("Part 2: " + similarityScore);

0 commit comments

Comments
 (0)