From 921a9ff1bd17c991739a8d3b5b25e65235b49bf5 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Wed, 3 Nov 2021 18:45:47 +0000 Subject: [rust] Bowling --- rust/bowling/src/lib.rs | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 rust/bowling/src/lib.rs (limited to 'rust/bowling/src/lib.rs') diff --git a/rust/bowling/src/lib.rs b/rust/bowling/src/lib.rs new file mode 100644 index 0000000..bd517a5 --- /dev/null +++ b/rust/bowling/src/lib.rs @@ -0,0 +1,45 @@ +#[derive(Debug, PartialEq)] +pub enum Error { + NotEnoughPinsLeft, + GameComplete, +} + +#[derive(Debug, Default)] +pub struct BowlingGame { + throws: Vec, + prev: u16 +} + +impl BowlingGame { + pub fn new() -> Self { + Default::default() + } + + pub fn roll(&mut self, pins: u16) -> Result<(), Error> { + if pins + self.prev > 10 { + Err(Error::NotEnoughPinsLeft) + } else if self.score().is_some() { + Err(Error::GameComplete) + } else { + self.throws.push(pins); + self.prev = if self.prev + pins == 10 { 0 } else { pins }; + Ok(()) + } + } + + pub fn score(&self) -> Option { + let mut score = 0; + let mut stage = 0; + for _ in 1..=10 { + let first = self.throws.get(stage)?; + let second = self.throws.get(stage+1)?; + score += first + second; + if first + second >= 10 { + let third = self.throws.get(stage+2)?; + score += third; + } + stage += if *first == 10 { 1 } else { 2 }; + } + Some(score) + } +} -- cgit v1.2.3