-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday11.rs
More file actions
108 lines (86 loc) · 2.75 KB
/
day11.rs
File metadata and controls
108 lines (86 loc) · 2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use std::collections::HashMap;
fn parse_input(input: &str) -> Vec<usize> {
let line = input.lines().next().unwrap();
line.split(' ')
.map(|number| number.parse::<usize>().unwrap())
.collect()
}
fn brute_force(input: &str, limit: usize) -> String {
let mut stones = parse_input(input);
for _ in 0..limit {
let mut new_stones = Vec::new();
for stone in stones {
if stone == 0 {
new_stones.push(1);
continue;
}
let str_stone = stone.to_string();
if str_stone.len() % 2 == 0 {
let (left, right) = str_stone.split_at(str_stone.len() / 2);
new_stones.push(left.parse::<usize>().unwrap());
new_stones.push(right.parse::<usize>().unwrap());
continue;
}
new_stones.push(stone * 2024)
}
stones = new_stones;
}
stones.len().to_string()
}
fn hashmap_based(input: &str, limit: usize) -> String {
let vec_stones = parse_input(input);
let mut stones: HashMap<usize, usize> =
HashMap::from_iter(vec_stones.iter().map(|&stone| (stone, 1)));
for _ in 0..limit {
let mut new_stones = HashMap::new();
for (&stone, &count) in stones.iter() {
if stone == 0 {
*new_stones.entry(1).or_insert(0) += count;
continue;
}
let str_stone = stone.to_string();
if str_stone.len() % 2 == 0 {
let (left, right) = str_stone.split_at(str_stone.len() / 2);
let left = left.parse::<usize>().unwrap();
let right = right.parse::<usize>().unwrap();
*new_stones.entry(left).or_insert(0) += count;
*new_stones.entry(right).or_insert(0) += count;
continue;
}
*new_stones.entry(stone * 2024).or_insert(0) += count;
}
stones = new_stones;
}
stones.values().sum::<usize>().to_string()
}
pub fn task01(input: &str) -> String {
brute_force(input, 25)
}
pub fn task02(input: &str) -> String {
hashmap_based(input, 75)
}
#[cfg(test)]
mod tests {
use super::super::fs_utils::{read_example, read_input};
use super::*;
#[test]
fn test_task01() {
let input = read_example(11, 1);
assert_eq!(task01(&input), "55312");
}
#[test]
fn run_task01() {
let input = read_input(11);
assert_eq!(task01(&input), "220722");
}
#[test]
fn test_task02() {
let input = read_example(11, 1);
assert_eq!(task02(&input), "65601038650482");
}
#[test]
fn run_task02() {
let input = read_input(11);
assert_eq!(task02(&input), "261952051690787");
}
}