-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.rs
56 lines (51 loc) · 1.49 KB
/
game.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::cmp::max;
use std::{str::FromStr, rc::Rc};
use crate::run::{Run,RunError};
#[derive(Debug)]
pub(crate) struct Game {
pub(crate) id: u32,
runs: Rc<[Run]>,
max: Run
}
impl Game {
pub(crate) fn is_feasible(&self, run: &Run) -> bool {
self.runs
.iter()
.all(|r| r.is_feasible(run) )
}
pub(crate) fn power(&self) -> u32 {
self.max.power()
}
}
impl FromStr for Game {
type Err = RunError;
/// should parse the string "Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green"
/// Game { 1, [ {(Blue,3),(Red,4)},{(Red,1),(Green,2),(Blue,6)},{(Green,2)} ]
fn from_str(input: &str) -> Result<Self, Self::Err> {
let Run{mut red, mut blue, mut green} = Run::default();
let mut gsplit = input.split(':');
let id = gsplit
.next().unwrap()
.split_ascii_whitespace()
.last().unwrap()
.parse::<u32>()?;
gsplit
.next().unwrap()
.split(';')
.map(|run| run.parse::<Run>())
.inspect(|run| {
if let Ok(run) = run {
red = max(red, run.red);
blue = max(blue, run.blue);
green = max(green, run.green);
}
})
.collect::<Result<Rc<_>,_>>()
.map(|runs|
Game {
id, runs,
max: Run { red, green, blue },
}
)
}
}