|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::fs; |
| 3 | +use std::path::Path; |
| 4 | + |
| 5 | +fn read_numbers() -> Vec<u64> { |
| 6 | + let current_file = Path::new(file!()); |
| 7 | + let current_dir = current_file |
| 8 | + .parent() |
| 9 | + .expect("Failed to get parent directory"); |
| 10 | + let file_path = current_dir.join("data.txt"); |
| 11 | + |
| 12 | + fs::read_to_string(file_path) |
| 13 | + .expect("Failed to read file") |
| 14 | + .split_whitespace() |
| 15 | + .map(|num| num.parse().expect("Failed to parse number")) |
| 16 | + .collect() |
| 17 | +} |
| 18 | + |
| 19 | +fn split(number: u64) -> Vec<u64> { |
| 20 | + if number == 0 { |
| 21 | + return vec![1]; |
| 22 | + } |
| 23 | + |
| 24 | + let number_str = number.to_string(); |
| 25 | + if number_str.len() % 2 == 0 { |
| 26 | + let half = number_str.len() / 2; |
| 27 | + let first = number_str[..half].parse().unwrap(); |
| 28 | + let second = number_str[half..].parse().unwrap(); |
| 29 | + vec![first, second] |
| 30 | + } else { |
| 31 | + vec![number * 2024] |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn blinking(numbers: Vec<u64>, until: usize) -> usize { |
| 36 | + let mut stones: HashMap<u64, usize> = HashMap::new(); |
| 37 | + for &n in &numbers { |
| 38 | + *stones.entry(n).or_insert(0) += 1; |
| 39 | + } |
| 40 | + |
| 41 | + for _ in 0..until { |
| 42 | + let mut new_stones: HashMap<u64, usize> = HashMap::new(); |
| 43 | + |
| 44 | + for (&n, &count) in stones.iter() { |
| 45 | + for split_num in split(n) { |
| 46 | + *new_stones.entry(split_num).or_insert(0) += count; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + stones = new_stones; |
| 51 | + } |
| 52 | + |
| 53 | + stones.values().sum() |
| 54 | +} |
| 55 | + |
| 56 | +fn main() { |
| 57 | + let numbers = read_numbers(); |
| 58 | + let result = blinking(numbers, 75); |
| 59 | + |
| 60 | + println!("{}", result); |
| 61 | +} |
0 commit comments