First day part 1 & 2 solutions

This commit is contained in:
Egor 2024-12-01 16:23:54 +03:00
commit 9f82abbd55
6 changed files with 1079 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

7
Cargo.lock generated Normal file
View file

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aoc2024"
version = "0.1.0"

6
Cargo.toml Normal file
View file

@ -0,0 +1,6 @@
[package]
name = "aoc2024"
version = "0.1.0"
edition = "2021"
[dependencies]

1000
input/day1.txt Normal file

File diff suppressed because it is too large Load diff

50
src/bin/day1.rs Normal file
View file

@ -0,0 +1,50 @@
use std::collections::{BinaryHeap, HashMap};
use aoc2024::solve;
fn main() {
solve(1, part1, part2);
}
const LINES_IN_INPUT: usize = 1000;
fn part1(input: &str) -> u64 {
let (mut list1, mut list2) = (
BinaryHeap::<u64>::with_capacity(LINES_IN_INPUT),
BinaryHeap::<u64>::with_capacity(LINES_IN_INPUT),
);
for line in input.lines() {
let elements: Vec<u64> = line
.split_whitespace()
.map(|s| s.parse::<u64>().unwrap())
.collect();
list1.push(elements[0]);
list2.push(elements[1]);
}
let mut distance = 0u64;
while !list1.is_empty() {
let (left, right) = (list1.pop().unwrap(), list2.pop().unwrap());
distance += left.abs_diff(right);
}
distance
}
fn part2(input: &str) -> u64 {
let mut list1 = Vec::<u64>::with_capacity(LINES_IN_INPUT);
let mut occurences = HashMap::<u64, u64>::with_capacity(LINES_IN_INPUT);
for line in input.lines() {
let elements: Vec<u64> = line
.split_whitespace()
.map(|s| s.parse::<u64>().unwrap())
.collect();
list1.push(elements[0]);
let value = occurences.entry(elements[1]).or_default();
*value += 1;
}
let mut score = 0u64;
for element in list1 {
let element_occurences = occurences.get(&element).map_or(0, |o| *o);
score += element * element_occurences;
}
score
}

15
src/lib.rs Normal file
View file

@ -0,0 +1,15 @@
use std::fmt::Display;
pub fn solve<F, G, FRet, GRet>(day: u8, part1: F, part2: G)
where
FRet: Display,
F: FnOnce(&str) -> FRet,
GRet: Display,
G: FnOnce(&str) -> GRet,
{
let filename = format!("input/day{day}.txt");
let input = std::fs::read_to_string(filename).unwrap();
println!("Day {day}");
println!("Part 1: {}", part1(&input));
println!("Part 2: {}", part2(&input));
}