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;
- const MAX_RED: usize = 12;
- const MAX_GREEN: usize = 13;
- const MAX_BLUE: usize = 14;
- struct Game {
- id: usize,
- hands: Vec<Hand>,
- }
- impl From<&String> for Game {
- fn from(s: &String) -> Self {
- let re = Regex::new(r"Game (\d+): (.+)$").unwrap();
- let matches = re.captures(&s).unwrap();
- let hands = matches[2]
- .split(";")
- .map(Hand::from)
- .collect::<Vec<_>>();
- Game {
- id: matches[1].parse().unwrap(),
- hands: hands,
- }
- }
- }
- impl Game {
- pub fn is_possible(&self) -> bool {
- self.hands.len() == self.hands.iter().filter(|h| h.is_valid()).count()
- }
- pub fn power(&self) -> usize {
- self.hands.iter().map(|x| x.red ).max().unwrap() *
- self.hands.iter().map(|x| x.green).max().unwrap() *
- self.hands.iter().map(|x| x.blue ).max().unwrap()
- }
- }
- struct Hand {
- red: usize,
- green: usize,
- blue: usize,
- }
- impl Hand {
- pub fn is_valid(&self) -> bool {
- self.red <= MAX_RED && self.green <= MAX_GREEN && self.blue <= MAX_BLUE
- }
- }
- impl From<&str> for Hand {
- fn from(s: &str) -> Self {
- Hand {
- red: cubes_for_color("red", &s),
- green: cubes_for_color("green",&s),
- blue: cubes_for_color("blue", &s),
- }
- }
- }
- fn cubes_for_color(color: &str, hand: &str) -> usize {
- let re = format!(r"(\d+) {color}");
- let re_color = Regex::new(&re).unwrap();
- if let Some(matches) = re_color.captures(hand) {
- return matches[1].parse().unwrap();
- }
- 0
- }
- 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,
- };
- let games: Vec<_> = input.iter().map(Game::from).collect();
- let part1: usize = games.iter().filter(|x| x.is_possible()).map(|g| g.id).sum();
- println!("Part 1: {part1}"); // 2369
- let part2: usize = games.iter().map(|g| g.power()).sum();
- println!("Part 2: {part2}"); // 66363
- 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