Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 16f2ab6

Browse files
committed
Add cybai's 2024 day 1 solution
1 parent 52b8814 commit 16f2ab6

File tree

3 files changed

+91
-0
lines changed

3 files changed

+91
-0
lines changed

‎2024/01/cybai/Cargo.toml‎

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

‎2024/01/cybai/day01.txt‎

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

‎2024/01/cybai/src/main.rs‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
use std::collections::HashMap;
2+
3+
fn main() {
4+
let input = include_str!("../day01.txt");
5+
6+
println!("Part 1: {}", part1(input));
7+
println!("Part 2: {}", part2(input));
8+
}
9+
10+
fn part1(input: &str) -> i32 {
11+
let (mut lefts, mut rights): (Vec<_>, Vec<_>) = input
12+
.lines()
13+
.map(|line| {
14+
let mut nums = line
15+
.split_whitespace()
16+
.map(|num| num.parse::<i32>().unwrap());
17+
let a = nums.next().unwrap();
18+
let b = nums.next().unwrap();
19+
20+
(a, b)
21+
})
22+
.unzip();
23+
24+
lefts.sort();
25+
rights.sort();
26+
27+
lefts
28+
.into_iter()
29+
.zip(rights)
30+
.fold(0, |acc, (a, b)| acc + (b - a).abs())
31+
}
32+
33+
fn part2(input: &str) -> i32 {
34+
let (lefts, rights): (Vec<_>, Vec<_>) = input
35+
.lines()
36+
.map(|line| {
37+
let mut nums = line
38+
.split_whitespace()
39+
.map(|num| num.parse::<i32>().unwrap());
40+
let a = nums.next().unwrap();
41+
let b = nums.next().unwrap();
42+
43+
(a, b)
44+
})
45+
.unzip();
46+
47+
let mut counts: HashMap<i32, i32> = HashMap::new();
48+
49+
for n in &lefts {
50+
if !counts.contains_key(n) {
51+
counts.insert(*n, 0);
52+
}
53+
}
54+
55+
for n in rights {
56+
if let Some(count) = counts.get_mut(&n) {
57+
*count += 1;
58+
}
59+
}
60+
61+
lefts.into_iter().map(|n| n * counts[&n]).sum()
62+
}
63+
64+
#[cfg(test)]
65+
mod tests {
66+
use super::*;
67+
68+
const TEST_INPUT: &str = "3 4
69+
4 3
70+
2 5
71+
1 3
72+
3 9
73+
3 3";
74+
75+
#[test]
76+
fn test_part1() {
77+
assert_eq!(part1(TEST_INPUT), 11);
78+
}
79+
80+
#[test]
81+
fn test_part2() {
82+
assert_eq!(part2(TEST_INPUT), 31);
83+
}
84+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /