-
-
Save huonw/aa297c12d8b82c76f494 to your computer and use it in GitHub Desktop.
Challenge #236 [Easy] Random Bag System
This file contains 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
extern crate rand; | |
use rand::Rng; | |
struct Bag { | |
contents: Vec<char>, | |
rng: rand::ThreadRng, | |
} | |
impl Bag { | |
fn new() -> Bag { | |
Bag { | |
contents: Vec::new(), | |
rng: rand::thread_rng(), | |
} | |
} | |
} | |
impl Iterator for Bag { | |
type Item = char; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.contents.is_empty() { | |
// replenish the data | |
// using extend like this will avoid allocating a whole new vector, | |
// it'll just reuse the memory of the old one | |
self.contents.extend(&['O', 'I', 'S', 'Z', 'L', 'J', 'T']); | |
self.rng.shuffle(&mut self.contents); | |
} | |
self.contents.pop() | |
} | |
} | |
fn main() { | |
for c in Bag::new().take(50) { | |
print!("{}", c); | |
} | |
print!("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment