Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::env;
- use std::io::{self, prelude::*, BufReader};
- use std::fs::File;
- extern crate regex;
- use regex::Regex;
- fn calibration_value(input: &str) -> usize {
- let re = Regex::new(r"(\d)").unwrap();
- let matches: Vec<_> = re
- .find_iter(input)
- .map(|x| x.as_str().parse::<usize>().ok())
- .collect();
- 10 * matches[0].unwrap() + matches[matches.len()-1].unwrap()
- }
- fn calibration_value_2(input: &str) -> usize {
- let re = Regex::new(r"(\d|one|two|three|four|five|six|seven|eight|nine)").unwrap();
- let matches: Vec<_> = re
- .find_iter(input)
- .map(|x| x.as_str())
- .collect();
- 10 * actual_value(matches[0]) + actual_value(matches[matches.len()-1])
- }
- fn actual_value(input: &str) -> usize {
- match input {
- "1" | "one" => 1,
- "2" | "two" => 2,
- "3" | "three" => 3,
- "4" | "four" => 4,
- "5" | "five" => 5,
- "6" | "six" => 6,
- "7" | "seven" => 7,
- "8" | "eight" => 8,
- "9" | "nine" => 9,
- _ => panic!("Unexpected input to actual_value: {input}"),
- }
- }
- fn solve(input: &str) -> io::Result<()> {
- let file = File::open(input).expect("Input file not found.");
- let reader = BufReader::new(file);
- // Input
- let input: Vec<String> = match reader.lines().collect() {
- Err(err) => panic!("Unknown error reading input: {}", err),
- Ok(result) => result,
- };
- // Part 1
- let part1 = input
- .iter()
- .map(|x| calibration_value(x))
- .sum::<usize>();
- println!("Part 1: {part1}"); // 54561
- // Part 2
- let part2 = input
- .iter()
- .map(|x| calibration_value_2(x))
- .sum::<usize>();
- println!("Part 2: {part2}"); // 54076
- Ok(())
- }
- fn main() {
- let args: Vec<String> = env::args().collect();
- let filename = &args[1];
- solve(&filename).unwrap();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement