1234567891011121314151617181920212223242526272829303132333435363738394041 |
- use std::collections::HashMap;
- use std::fs;
- fn find_nth(numbers: &[usize], end: usize) -> usize {
- let numbers: Vec<usize> = numbers.iter().map(|i| *i).collect();
- let mut last_spoken: HashMap<usize, usize> = HashMap::new();
- let mut last: usize = *numbers.last().unwrap();
- let mut numbers: Vec<usize> = numbers[0..numbers.len() - 1].iter().map(|i| *i).collect();
- for (i, num) in numbers.iter().enumerate() {
- last_spoken.insert(*num, i);
- }
- for i in numbers.len()..end {
- let next = match last_spoken.get(&(last)) {
- Some(index) => i - index,
- None => 0,
- };
- numbers.push(last);
- last_spoken.insert(last, i);
- last = next;
- }
- *numbers.last().unwrap()
- }
- fn main() {
- let num_str = fs::read_to_string("15.input").unwrap();
- let num_str = num_str.trim();
- let nums: Vec<usize> = num_str
- .split(",")
- .map(|s| s.parse::<usize>().unwrap())
- .collect();
- println!("Answer 1: {}", find_nth(&nums, 2020));
- println!("Answer 2: {}", find_nth(&nums, 30000000));
- }
|