Skip to content

Commit

Permalink
Solve 2024 day 1 part 1
Browse files Browse the repository at this point in the history
jeffs committed Dec 1, 2024
1 parent 6e28ddb commit 6edf60e
Showing 7 changed files with 1,064 additions and 0 deletions.
7 changes: 7 additions & 0 deletions 2024/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions 2024/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[workspace]
members = ["day1"]
resolver = "2"
6 changes: 6 additions & 0 deletions 2024/day1/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "day1"
version = "0.1.0"
edition = "2021"

[dependencies]
1 change: 1 addition & 0 deletions 2024/day1/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod part1;
6 changes: 6 additions & 0 deletions 2024/day1/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
use day1::part1;

fn main() {
let s = include_str!("part1/input");
println!("{}", part1::solve(&s).unwrap());
}
41 changes: 41 additions & 0 deletions 2024/day1/src/part1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#[derive(Debug)]
pub enum Error {
BadLine,
}

type Result<T> = std::result::Result<T, Error>;

pub fn distance(xs: impl Into<Vec<u32>>, ys: impl Into<Vec<u32>>) -> u32 {
let (mut xs, mut ys) = (xs.into(), ys.into());
debug_assert_eq!(xs.len(), ys.len());
xs.sort();
ys.sort();
xs.iter().zip(ys.iter()).map(|(x, y)| x.abs_diff(*y)).sum()
}

pub fn solve(input: &str) -> Result<u32> {
let mut xs = Vec::new();
let mut ys = Vec::new();
for line in input.lines() {
let mut parts = line.split_ascii_whitespace();
let (Some(x), Some(y), None) = (parts.next(), parts.next(), parts.next()) else {
return Err(Error::BadLine);
};
let (Ok(x), Ok(y)) = (x.parse::<u32>(), y.parse::<u32>()) else {
return Err(Error::BadLine);
};
xs.push(x);
ys.push(y);
}
Ok(distance(xs, ys))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_distance() {
assert_eq!(distance([3, 4, 2, 1, 3, 3], [4, 3, 5, 3, 9, 3]), 11);
}
}
Loading
Oops, something went wrong.

0 comments on commit 6edf60e

Please sign in to comment.