Skip to content

Commit cfbd90d

Browse files
committed
Add day 01
1 parent 39a02a4 commit cfbd90d

File tree

2 files changed

+79
-4
lines changed

2 files changed

+79
-4
lines changed

data/examples/01.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
3 4
2+
4 3
3+
2 5
4+
1 3
5+
3 9
6+
3 3

src/bin/01.rs

Lines changed: 73 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,80 @@
1+
use std::collections::HashMap;
2+
13
advent_of_code::solution!(1);
24

35
pub fn part_one(input: &str) -> Option<u32> {
4-
None
6+
// println!("{}", input);
7+
let mut column1 = Vec::new();
8+
let mut column2 = Vec::new();
9+
10+
for line in input.lines(){
11+
// let line = line?;
12+
let numbers: Vec<i32> = line
13+
.split_whitespace()
14+
.filter_map(|s| s.parse().ok())
15+
.collect();
16+
17+
if numbers.len() == 2 { // Ensure we have two numbers
18+
column1.push(numbers[0].clone());
19+
column2.push(numbers[1].clone());
20+
}
21+
}
22+
println!("{:?}", column1);
23+
println!("{:?}", column2);
24+
25+
column1.sort();//sort_by(|a, b| a.cmp(b));
26+
column2.sort();// (|a, b| a.cmp(b));
27+
28+
// let result:i32 = column1.iter()
29+
// .zip(column1.iter())
30+
// .map(|(&left, &right)| (left - right).abs())
31+
// .sum();
32+
let mut result: i32 = 0;
33+
for i in 0..column1.len() {
34+
let left = column1[i];
35+
let right = column2[i];
36+
result += (left - right).abs();
37+
}
38+
39+
Some(result as u32)
540
}
641

742
pub fn part_two(input: &str) -> Option<u32> {
8-
None
43+
let mut column1 = Vec::new();
44+
let mut column2 = Vec::new();
45+
46+
for line in input.lines(){
47+
// let line = line?;
48+
let numbers: Vec<i32> = line
49+
.split_whitespace()
50+
.filter_map(|s| s.parse().ok())
51+
.collect();
52+
53+
if numbers.len() == 2 {
54+
column1.push(numbers[0].clone());
55+
column2.push(numbers[1].clone());
56+
}
57+
}
58+
// println!("{:?}", column1);
59+
// println!("{:?}", column2);
60+
61+
column1.sort();
62+
column2.sort();
63+
64+
let mut count_map = HashMap::new();
65+
for &num in &column2 {
66+
*count_map.entry(num).or_insert(0) += 1;
67+
}
68+
69+
let mut result: i32 = 0;
70+
for i in 0..column1.len() {
71+
let left = column1[i];
72+
73+
let count = count_map.get(&left).unwrap_or(&0);
74+
result += left *count;
75+
}
76+
77+
Some(result as u32)
978
}
1079

1180
#[cfg(test)]
@@ -15,12 +84,12 @@ mod tests {
1584
#[test]
1685
fn test_part_one() {
1786
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
18-
assert_eq!(result, None);
87+
assert_eq!(result, Some(11));
1988
}
2089

2190
#[test]
2291
fn test_part_two() {
2392
let result = part_two(&advent_of_code::template::read_file("examples", DAY));
24-
assert_eq!(result, None);
93+
assert_eq!(result, Some(31));
2594
}
2695
}

0 commit comments

Comments
 (0)