15.rs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. use std::collections::HashMap;
  2. use std::fs;
  3. fn find_nth(numbers: &[usize], end: usize) -> usize {
  4. let numbers: Vec<usize> = numbers.iter().map(|i| *i).collect();
  5. let mut last_spoken: HashMap<usize, usize> = HashMap::new();
  6. let mut last: usize = *numbers.last().unwrap();
  7. let mut numbers: Vec<usize> = numbers[0..numbers.len() - 1].iter().map(|i| *i).collect();
  8. for (i, num) in numbers.iter().enumerate() {
  9. last_spoken.insert(*num, i);
  10. }
  11. for i in numbers.len()..end {
  12. let next = match last_spoken.get(&(last)) {
  13. Some(index) => i - index,
  14. None => 0,
  15. };
  16. numbers.push(last);
  17. last_spoken.insert(last, i);
  18. last = next;
  19. }
  20. *numbers.last().unwrap()
  21. }
  22. fn main() {
  23. let num_str = fs::read_to_string("15.input").unwrap();
  24. let num_str = num_str.trim();
  25. let nums: Vec<usize> = num_str
  26. .split(",")
  27. .map(|s| s.parse::<usize>().unwrap())
  28. .collect();
  29. println!("Answer 1: {}", find_nth(&nums, 2020));
  30. println!("Answer 2: {}", find_nth(&nums, 30000000));
  31. }