This commit is contained in:
Tobias Berger 2024-12-01 15:20:16 +01:00
parent a4459a59d1
commit b0210d263f
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
3 changed files with 1097 additions and 1 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
authors = ["Toby <toby@tobot.dev>"] authors = ["Toby <toby@tobot.dev>"]
name = "advent-of-code-2024" name = "advent-of-code-2024"
version = "24.0.0" version = "24.1.2"
edition = "2021" edition = "2021"
default-run = "get_input" default-run = "get_input"
@ -31,6 +31,10 @@ name = "template"
path = "src/day00/main.rs" path = "src/day00/main.rs"
test = false test = false
[[bin]]
name = "day01"
path = "src/day01/main.rs"
[dependencies] [dependencies]
reqwest = { version = "0.12.9", features = ["blocking"] } reqwest = { version = "0.12.9", features = ["blocking"] }

1000
src/day01/input.txt Normal file

File diff suppressed because it is too large Load diff

92
src/day01/main.rs Normal file
View file

@ -0,0 +1,92 @@
pub const INPUT: &str = include_str!("./input.txt");
fn parse_input(input: &'static str) -> Vec<[u32; 2]> {
let input = input
.lines()
.map(|line| -> [u32; 2] {
let nums = line
.split_whitespace()
.map(|num| num.parse::<u32>().unwrap())
.collect::<Vec<_>>();
[nums[0], nums[1]]
})
.collect::<Vec<_>>();
input
}
pub fn main() {
let input = parse_input(INPUT);
let result_1 = part_1(&input);
println!("{result_1}");
let result_2 = part_2(&input);
println!("{result_2}");
}
fn part_1(input: &Vec<[u32; 2]>) -> u32 {
let mut left = vec![];
let mut right = vec![];
for pair in input {
left.push(pair[0]);
right.push(pair[1]);
}
left.sort_unstable();
right.sort_unstable();
let mut diff = 0;
for i in 0..left.len() {
diff += u32::abs_diff(left[i], right[i]);
}
diff
}
fn part_2(input: &Vec<[u32; 2]>) -> u32 {
let mut left = vec![];
let mut right = vec![];
for pair in input {
left.push(pair[0]);
right.push(pair[1]);
}
let mut result = 0;
for num in left {
result += num * right.iter().filter(|&&x| x == num).count() as u32;
}
result
}
#[cfg(test)]
mod tests {
use crate::parse_input;
const SAMPLE_INPUT: &str = r#"3 4
4 3
2 5
1 3
3 9
3 3"#;
#[test]
fn test_part_1_with_sample_solution() {
let input = parse_input(SAMPLE_INPUT);
assert_eq!(super::part_1(&input), 11)
}
#[test]
fn test_part_1_with_solution() {
let input = parse_input(super::INPUT);
assert_eq!(super::part_1(&input), 2192892);
}
#[test]
fn test_part_2_with_sample_solution() {
let input = parse_input(SAMPLE_INPUT);
assert_eq!(super::part_2(&input), 31)
}
#[test]
fn test_part_2_with_solution() {
let input = parse_input(super::INPUT);
assert_eq!(super::part_2(&input), 22962826);
}
}