day02: Add part 2

I suspect there must be a better way which could present this more
generically e.g. if I could iterate over the enum somehow ...
2022
MasterofJOKers 1 year ago
parent 1001e9dd0f
commit 7b82a1f46b

@ -17,9 +17,6 @@ impl Values {
"A" => Values::Rock,
"B" => Values::Paper,
"C" => Values::Scissors,
"X" => Values::Rock,
"Y" => Values::Paper,
"Z" => Values::Scissors,
_ => panic!("Unexpected value for Values")
}
}
@ -28,23 +25,61 @@ impl Values {
match self {
Values::Rock => 1,
Values::Paper => 2,
Values::Scissors => 3
Values::Scissors => 3,
}
}
fn beats(self, other: Values) -> bool {
if self == Values::Rock {
other == Values::Scissors
} else if self == Values::Paper {
other == Values::Rock
} else if self == Values::Scissors {
other == Values::Paper
} else {
false
fn get_other(&self, play_result: &PlayResult) -> Values {
match self {
Values::Rock => {
match play_result {
PlayResult::Lose => Values::Scissors,
PlayResult::Draw => Values::Rock,
PlayResult::Win => Values::Paper
}
},
Values::Paper => {
match play_result {
PlayResult::Lose => Values::Rock,
PlayResult::Draw => Values::Paper,
PlayResult::Win => Values::Scissors
}
},
Values::Scissors => {
match play_result {
PlayResult::Lose => Values::Paper,
PlayResult::Draw => Values::Scissors,
PlayResult::Win => Values::Rock,
}
},
}
}
}
enum PlayResult {
Lose,
Draw,
Win,
}
impl PlayResult {
fn get_from_str(v: &str) -> PlayResult {
match v {
"X" => PlayResult::Lose,
"Y" => PlayResult::Draw,
"Z" => PlayResult::Win,
_ => panic!("Unexpected value for PlayResult")
}
}
fn get_u32(&self) -> u32 {
match self {
PlayResult::Lose => 0,
PlayResult::Draw => 3,
PlayResult::Win => 6
}
}
}
fn main() -> Result<(), Box<dyn error::Error>> {
let f = File::open("input.txt")?;
@ -53,15 +88,13 @@ fn main() -> Result<(), Box<dyn error::Error>> {
let mut sum: u32 = 0;
for line in reader.lines() {
let line = line?;
let mut split_result = line.split_whitespace().map(|o| Values::get_from_str(o));
let other = split_result.next().unwrap();
let my = split_result.next().unwrap();
let split_result = line.split_whitespace().collect::<Vec<&str>>();
let other = Values::get_from_str(split_result[0]);
let play_result = PlayResult::get_from_str(split_result[1]);
let my = other.get_other(&play_result);
sum += my.get_u32();
if other == my {
sum += 3;
} else if my.beats(other) {
sum += 6;
}
sum += play_result.get_u32();
}
println!("{}", sum);

Loading…
Cancel
Save