day10.rs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use std::io;
  2. use std::io::BufRead;
  3. fn part1(adapters: &Vec<i32>) -> usize {
  4. let mut current = 0;
  5. let mut by_1 = 0;
  6. let mut by_3 = 0;
  7. for voltage in adapters {
  8. let jump = voltage - current;
  9. match jump {
  10. 1 => by_1 += 1,
  11. 3 => by_3 += 1,
  12. _ => {},
  13. }
  14. current = *voltage;
  15. }
  16. // dbg!(by_1);
  17. // dbg!(by_3);
  18. by_1 * by_3
  19. }
  20. fn main() {
  21. let mut adapters: Vec<i32> = io::stdin().lock().lines()
  22. .map(|l| l.unwrap().parse::<i32>().unwrap())
  23. .collect();
  24. adapters.sort();
  25. adapters.push(adapters[adapters.len() - 1] + 3);
  26. println!("Part 1: {}", part1(&adapters));
  27. // find subsequences where each step difference is < 3
  28. let mut i = 0;
  29. let mut combo_product = 1u64;
  30. // to make the first element after the power outlet skippable too
  31. adapters.insert(0, 0);
  32. while i < adapters.len() - 2 {
  33. let mut j = i;
  34. while adapters[j + 1] - adapters[j] < 3 {
  35. j += 1;
  36. }
  37. let subseq_len = j - i + 1;
  38. // mostly reverse-enginneered from the examples :/
  39. // subseqs of length 3 have 2 possible valid variants,
  40. // those of length 4 have 4, those of 5 have 7,
  41. // and longer ones didn't show up in any input data
  42. combo_product *= match subseq_len {
  43. 3 => 2u64,
  44. 4 => 4u64,
  45. 5 => 7u64,
  46. _ => 1u64,
  47. };
  48. // dbg!(subseq_len);
  49. // dbg!(&adapters[i..=j]);
  50. i = j + 1;
  51. }
  52. println!("Part 2: {}", combo_product);
  53. }