Skip to content

Commit fd2fdff

Browse files
committed
initial commit with day 1
1 parent 6e6495a commit fd2fdff

File tree

6 files changed

+74
-1
lines changed

6 files changed

+74
-1
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/target
2+
Cargo.lock

Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "aoc"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]

README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
1-
# aoc
1+
# Advent of Code
2+
Solutions for Advent of Code, with my puzzle data included. Run it like this:
3+
```
4+
cargo run
5+
```
6+
Output:
7+
```
8+
Compiling aoc v0.1.0 (/home/frank/data/projects/aoc)
9+
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.42s
10+
Running `target/debug/aoc`
11+
solution 1: 1834060
12+
solution 2: 21607792
13+
```

src/main.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
use std::fs;
2+
mod year2024;
3+
4+
fn main() {
5+
// read input
6+
let file = fs::read_to_string("src/year2024/day1.txt").unwrap();
7+
let lines = file.lines().collect();
8+
9+
// calculate solution
10+
let (solution1, solution2) = year2024::day1::solve(lines);
11+
12+
// show it
13+
println!("solution 1: {}", solution1);
14+
println!("solution 2: {}", solution2);
15+
}

src/year2024/day1.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
use std::collections::HashMap;
2+
3+
pub fn solve(lines: Vec::<&str>) -> (String, String) {
4+
// split each line and store it in 2 int vectors
5+
let mut left = Vec::new();
6+
let mut right = Vec::new();
7+
for line in lines {
8+
let mut parts = line.split_whitespace();
9+
left.push(parts.next().unwrap().parse::<i32>().unwrap());
10+
right.push(parts.next().unwrap().parse::<i32>().unwrap());
11+
}
12+
13+
// sort vectors in-place
14+
left.sort();
15+
right.sort();
16+
17+
// sum differences
18+
let mut solution1 = 0;
19+
for i in 0..left.len() {
20+
solution1 += (left[i] - right[i]).abs();
21+
}
22+
23+
// create histogram
24+
let mut counts = HashMap::<i32, i32>::new();
25+
for i in right {
26+
*counts.entry(i).or_default() += 1;
27+
}
28+
29+
// sum each left entry by number of occurences in right vector
30+
let mut solution2 = 0;
31+
for i in left {
32+
solution2 += *counts.entry(i).or_default() * i;
33+
}
34+
35+
// return solutions
36+
(solution1.to_string(), solution2.to_string())
37+
}

src/year2024/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub mod day1;

0 commit comments

Comments
 (0)