Add day1
This commit is contained in:
32
2024/day1/src/main.rs
Normal file
32
2024/day1/src/main.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::fs;
|
||||
|
||||
fn main() {
|
||||
let input = fs::read_to_string("./input.txt").unwrap();
|
||||
let mut column1 = Vec::new();
|
||||
let mut column2 = Vec::new();
|
||||
for line in input.lines() {
|
||||
let mut split = line.split_whitespace();
|
||||
column1.push(split.next().unwrap().parse::<i32>().unwrap());
|
||||
column2.push(split.next().unwrap().parse::<i32>().unwrap());
|
||||
}
|
||||
column1.sort_unstable();
|
||||
column2.sort_unstable();
|
||||
|
||||
println!("Solution 1: {}", puzzle1(&column1, &column2));
|
||||
println!("Solution 2: {}", puzzle2(&column1, &column2));
|
||||
}
|
||||
|
||||
fn puzzle1(column1: &[i32], column2: &[i32]) -> i32 {
|
||||
column1
|
||||
.iter()
|
||||
.zip(column2)
|
||||
.map(|(c1, c2)| (c1 - c2).abs())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn puzzle2(column1: &[i32], column2: &[i32]) -> i32 {
|
||||
column1
|
||||
.iter()
|
||||
.map(|c1| column2.iter().filter(|&c2| c1 == c2).count() as i32 * c1)
|
||||
.sum()
|
||||
}
|
Reference in New Issue
Block a user