Skip to content

Instantly share code, notes, and snippets.

@huonw
Forked from RustyRails/main.rs
Created October 13, 2015 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huonw/aa297c12d8b82c76f494 to your computer and use it in GitHub Desktop.
Save huonw/aa297c12d8b82c76f494 to your computer and use it in GitHub Desktop.
Challenge #236 [Easy] Random Bag System
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