adventofcode2022/day02/part1.rs

107 lines
2.8 KiB
Rust

// Copyright 2022 Christian Ulrich
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// usage: ./part1 < input
use std::convert::TryFrom;
use std::io;
#[derive(Debug, Clone, Copy)]
enum Item {
Rock = 1,
Paper = 2,
Scissors = 3,
}
enum Outcome {
Lose = 0,
Draw = 3,
Win = 6,
}
struct Round {
me: Item,
other: Item,
}
struct Rounds {}
impl TryFrom<&str> for Item {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"A" | "X" => Ok(Item::Rock),
"B" | "Y" => Ok(Item::Paper),
"C" | "Z" => Ok(Item::Scissors),
_ => Err("invalid value"),
}
}
}
impl Round {
pub fn new(me: Item, other: Item) -> Self {
Self {
me: me,
other: other,
}
}
fn outcome(&self) -> Outcome {
match (self.me, self.other) {
(Item::Rock, Item::Paper) => Outcome::Lose,
(Item::Rock, Item::Scissors) => Outcome::Win,
(Item::Paper, Item::Rock) => Outcome::Win,
(Item::Paper, Item::Scissors) => Outcome::Lose,
(Item::Scissors, Item::Rock) => Outcome::Lose,
(Item::Scissors, Item::Paper) => Outcome::Win,
_ => Outcome::Draw,
}
}
pub fn score(&self) -> usize {
self.outcome() as usize + self.me as usize
}
}
impl Iterator for Rounds {
type Item = Result<Round, &'static str>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(line) = io::stdin().lines().next() {
let line = line.unwrap();
if line.len() > 0 {
if let Some((left, right)) = line.split_once(' ') {
if let (Ok(other), Ok(me)) = (Item::try_from(left), Item::try_from(right)) {
return Some(Ok(Round::new(me, other)));
}
}
return Some(Err("input file contains invalid line"));
}
}
None
}
}
fn main() -> Result<(), &'static str> {
let rounds = Rounds {};
let mut result = 0;
for round in rounds {
result += round?.score();
}
println!("{result}");
Ok(())
}