You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
advent-of-code/rust/src/lib.rs

65 lines
1.2 KiB

use std::io::Error;
9 years ago
use std::str::Chars;
pub trait Day {
fn new(String) -> Self;
fn solve(self) -> Result<i32, Error>;
}
pub struct Day01 {
input: String,
}
impl Day for Day01 {
fn new(input: String) -> Day01 {
Day01 { input: input }
}
fn solve(self) -> Result<i32, Error> {
9 years ago
let elevator = Elevator::new(self.input);
9 years ago
Ok(1 + elevator.run().position(|f| f == -1).unwrap_or(0) as i32)
9 years ago
}
}
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<i32> {
match self.chars.next() {
Some('(') => {
self.floor += 1;
Some(self.floor)
},
Some(')') => {
self.floor -= 1;
Some(self.floor)
},
_ => {
None
},
}
}
}