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;
- #[derive(Debug,PartialEq,Eq)]
- enum GameResult {
- Win = 6,
- Draw = 3,
- Lose = 0,
- }
- impl From<&str> for GameResult {
- fn from(c: &str) -> Self {
- match c {
- "X" => Self::Lose,
- "Y" => Self::Draw,
- "Z" => Self::Win,
- other => panic!("Unknown directive: {}",other),
- }
- }
- }
- #[derive(Copy,Clone,Debug,PartialEq,Eq)]
- enum Play {
- Rock = 1,
- Paper = 2,
- Scissors = 3,
- }
- impl From<&str> for Play {
- fn from(c: &str) -> Self {
- match c {
- "A" | "X" => Self::Rock,
- "B" | "Y" => Self::Paper,
- "C" | "Z" => Self::Scissors,
- other => panic!("Unknown play: {}",other),
- }
- }
- }
- // plays: (their play, my play)
- fn result(plays: &(Play,Play)) -> GameResult {
- use Play::*;
- use GameResult::*;
- match plays {
- (Rock,Rock) | (Paper,Paper) | (Scissors,Scissors) => { Draw },
- (Rock,Paper) => { Win },
- (Rock,Scissors) => { Lose },
- (Paper,Rock) => { Lose },
- (Paper,Scissors) => { Win },
- (Scissors,Rock) => { Win },
- (Scissors,Paper) => { Lose },
- }
- }
- fn play_from_result(their_play: Play, result: &GameResult) -> Play {
- use Play::*;
- use GameResult::*;
- match result {
- Draw => their_play,
- Win => {
- match their_play {
- Rock => Paper,
- Paper => Scissors,
- Scissors => Rock,
- }},
- Lose => {
- match their_play {
- Rock => Scissors,
- Paper => Rock,
- Scissors => Paper,
- }},
- }
- }
- fn plays(s: &String) -> (Play,Play) {
- let plays: Vec<_> = s.split_whitespace().collect();
- (Play::from(plays[0]), Play::from(plays[1]))
- }
- fn play_and_result(s: &String) -> (Play,GameResult) {
- let play_and_result: Vec<_> = s.split_whitespace().collect();
- (Play::from(play_and_result[0]), GameResult::from(play_and_result[1]))
- }
- 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| {
- let (their_play,my_play) = plays(x);
- let result = result(&(their_play,my_play));
- my_play as usize + result as usize
- })
- .sum::<usize>();
- println!("Part 1: {}", part1); // 11906
- // Part 2
- let part2 = input
- .iter()
- .map(|x| {
- let (play,result) = play_and_result(x);
- let my_play = play_from_result(play,&result);
- my_play as usize + result as usize
- })
- .sum::<usize>();
- println!("Part 2: {}", part2); // 11186
- 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