From 0eb87d8166daa394c66ebaef4629cfdf3c256f87 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Sun, 27 Dec 2015 22:20:11 -0800 Subject: [PATCH] Move Day 1 into its own file/module --- rust/src/day_01.rs | 61 +++++++++++++++++++++++++++++++++++++++++++++ rust/src/lib.rs | 62 ++-------------------------------------------- 2 files changed, 63 insertions(+), 60 deletions(-) create mode 100644 rust/src/day_01.rs diff --git a/rust/src/day_01.rs b/rust/src/day_01.rs new file mode 100644 index 0000000..8910258 --- /dev/null +++ b/rust/src/day_01.rs @@ -0,0 +1,61 @@ +use std::io; +use std::str::Chars; + +use day; + +pub struct Day01 { + input: String, +} + +impl day::Day for Day01 { + fn new(input: String) -> Day01 { + Day01 { input: input } + } + + fn solve(self) -> io::Result { + let elevator = Elevator::new(self.input); + Ok(1 + elevator.run().position(|f| f == -1).unwrap_or(0) as i32) + } +} + +struct Elevator { + instructions: String, +} + +impl<'a> Elevator { + fn new(input: String) -> Self { + Elevator { instructions: input } + } + + fn run(self: &'a Self) -> ElevatorIterator<'a> { + ElevatorIterator { + chars: self.instructions.chars(), + floor: 0, + } + } +} + +struct ElevatorIterator<'a> { + chars: Chars<'a>, + floor: i32, +} + +impl<'a> Iterator for ElevatorIterator<'a> { + type Item = i32; + + fn next(&mut self) -> Option { + match self.chars.next() { + Some('(') => { + self.floor += 1; + Some(self.floor) + }, + Some(')') => { + self.floor -= 1; + Some(self.floor) + }, + _ => { + None + }, + } + } +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 0d90e1b..2ecb3fd 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -1,63 +1,5 @@ -use std::io; -use std::str::Chars; - pub use day::Day; +pub use day_01::Day01; mod day; - -pub struct Day01 { - input: String, -} - -impl day::Day for Day01 { - fn new(input: String) -> Day01 { - Day01 { input: input } - } - - fn solve(self) -> io::Result { - let elevator = Elevator::new(self.input); - Ok(1 + elevator.run().position(|f| f == -1).unwrap_or(0) as i32) - } -} - -struct Elevator { - instructions: String, -} - -impl<'a> Elevator { - fn new(input: String) -> Self { - Elevator { instructions: input } - } - - fn run(self: &'a Self) -> ElevatorIterator<'a> { - ElevatorIterator { - chars: self.instructions.chars(), - floor: 0, - } - } -} - -struct ElevatorIterator<'a> { - chars: Chars<'a>, - floor: i32, -} - -impl<'a> Iterator for ElevatorIterator<'a> { - type Item = i32; - - fn next(&mut self) -> Option { - match self.chars.next() { - Some('(') => { - self.floor += 1; - Some(self.floor) - }, - Some(')') => { - self.floor -= 1; - Some(self.floor) - }, - _ => { - None - }, - } - } -} +mod day_01;