Advertisement
nairby

AOC 2023 Day 1

Dec 1st, 2023 (edited)
1,182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.92 KB | None | 0 0
  1. use std::env;
  2. use std::io::{self, prelude::*, BufReader};
  3. use std::fs::File;
  4.  
  5. extern crate regex;
  6. use regex::Regex;
  7.  
  8. fn calibration_value(input: &str) -> usize {
  9.     let re = Regex::new(r"(\d)").unwrap();
  10.     let matches: Vec<_> = re
  11.         .find_iter(input)
  12.         .map(|x| x.as_str().parse::<usize>().ok())
  13.         .collect();
  14.     10 * matches[0].unwrap() + matches[matches.len()-1].unwrap()
  15. }
  16.  
  17. fn calibration_value_2(input: &str) -> usize {
  18.     let re = Regex::new(r"(\d|one|two|three|four|five|six|seven|eight|nine)").unwrap();
  19.     let matches: Vec<_> = re
  20.         .find_iter(input)
  21.         .map(|x| x.as_str())
  22.         .collect();
  23.     10 * actual_value(matches[0]) + actual_value(matches[matches.len()-1])
  24. }
  25.  
  26. fn actual_value(input: &str) -> usize {
  27.     match input {
  28.         "1" | "one"   => 1,
  29.         "2" | "two"   => 2,
  30.         "3" | "three" => 3,
  31.         "4" | "four"  => 4,
  32.         "5" | "five"  => 5,
  33.         "6" | "six"   => 6,
  34.         "7" | "seven" => 7,
  35.         "8" | "eight" => 8,
  36.         "9" | "nine"  => 9,
  37.         _ => panic!("Unexpected input to actual_value: {input}"),
  38.     }
  39. }
  40.  
  41. fn solve(input: &str) -> io::Result<()> {
  42.     let file = File::open(input).expect("Input file not found.");
  43.     let reader = BufReader::new(file);
  44.  
  45.     // Input
  46.     let input: Vec<String> = match reader.lines().collect() {
  47.         Err(err) => panic!("Unknown error reading input: {}", err),
  48.         Ok(result) => result,
  49.     };
  50.  
  51.     // Part 1
  52.     let part1 = input
  53.         .iter()
  54.         .map(|x| calibration_value(x))
  55.         .sum::<usize>();
  56.     println!("Part 1: {part1}"); // 54561
  57.  
  58.     // Part 2
  59.     let part2 = input
  60.         .iter()
  61.         .map(|x| calibration_value_2(x))
  62.         .sum::<usize>();
  63.     println!("Part 2: {part2}"); // 54076
  64.  
  65.     Ok(())
  66. }
  67.  
  68. fn main() {
  69.     let args: Vec<String> = env::args().collect();
  70.     let filename = &args[1];
  71.     solve(&filename).unwrap();
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement