Skip to content

Instantly share code, notes, and snippets.

@pfalabella
Created May 29, 2014 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfalabella/c7f53c43c9f46cbf8fe5 to your computer and use it in GitHub Desktop.
Save pfalabella/c7f53c43c9f46cbf8fe5 to your computer and use it in GitHub Desktop.
100 doors Enterprise Edition
// Implements http://rosettacode.org/wiki/100_doors
#[cfg(not(test))]
fn main() {
let mut hd = HammingDoor :: new(0u);
for door in hd.iter().take(100) {
let state = if door.state() {"open"} else {"closed"};
println!("Door {} is {}", door.index, state);
}
}
struct HammingDoorIterator <'a> {
current: &'a mut HammingDoor
}
struct HammingDoor {
index: uint,
}
impl HammingDoor {
fn new(index: uint) -> HammingDoor {
HammingDoor {index: index}
}
fn iter<'a>(&'a mut self) -> HammingDoorIterator<'a> { HammingDoorIterator{current: self} }
fn state(&self) -> bool {
let sq = (self.index as f64).powf(0.5);
sq == sq.round()
}
}
impl <'a> Iterator<HammingDoor> for HammingDoorIterator <'a> {
fn next(&mut self) -> Option<HammingDoor> {
self.current.index += 1;
Some(*self.current)
}
}
#[test]
fn create_door() {
let hd= HammingDoor::new(4);
assert!(hd.index==4);
assert!(hd.state());
}
#[test]
fn test_iterator() {
let mut hd = HammingDoor :: new(0u);
let door=hd.iter().nth(99).unwrap();
assert!(door.index==100);
assert!(door.state());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment