Created
August 13, 2019 22:08
-
-
Save GoldsteinE/8ce297b375f5408568a75756c87c4cb8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
const WINDOW_SIZE: usize = 10; | |
struct FloatingWindow { | |
data: [i64; WINDOW_SIZE], | |
start_index: usize, | |
current_size: usize, | |
} | |
impl FloatingWindow { | |
pub fn new() -> Self { | |
Self { | |
start_index: 0, | |
current_size: 0, | |
} | |
} | |
pub fn at(&self, idx: usize) -> i64 { | |
self.data[(self.start_index + idx) % WINDOW_SIZE] | |
} | |
pub fn push(&mut self, value: i64) { | |
self.data[(self.start_index + self.current_size) % WINDOW_SIZE] = value; | |
if self.current_size < WINDOW_SIZE { | |
self.current_size += 1; | |
} else { | |
self.start_index += 1; | |
} | |
} | |
} | |
struct FloatingWindowIterator<'a> { | |
window: &'a FloatingWindow, | |
curr_index: usize | |
} | |
impl<'a> IntoIterator for &'a FloatingWindow { | |
type Item = i64; | |
type IntoIter = FloatingWindowIterator<'a>; | |
fn into_iter(self) -> Self::IntoIter { | |
FloatingWindowIterator::new(self) | |
} | |
} | |
impl<'a> FloatingWindowIterator<'a> { | |
pub fn new(window: &'a FloatingWindow) -> Self<'a> { | |
Self { | |
window, | |
curr_index: 0 | |
} | |
} | |
} | |
impl<'a> Iterator for FloatingWindowIterator<'a> { | |
type Item = i64; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.curr_index < self.window.current_size { | |
self.curr_index += 1; | |
Some(self.window.at(self.curr_index)) | |
} else { | |
None | |
} | |
} | |
} | |
fn main() { | |
let stdin = io::stdin(); | |
let mut user_input = String::new(); | |
let mut window = FloatingWindow::new(); | |
loop { | |
stdin.read_line(&mut user_input).expect("I/O Error"); | |
user_input = user_input.trim(); | |
if user_input == "p" { | |
for (idx, value) in &window.into_iter().enumerate() { | |
println!("{}: {}", idx, value); | |
} | |
} else { | |
match user_input.parse<i64>() { | |
Ok(num) => window.push(num), | |
Err(err) => eprintln!("Error parsing number: {}", err) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment