Skip to content

Instantly share code, notes, and snippets.

@mre
Created October 25, 2017 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mre/f9e8d31cd1bde76fc714cae3f9d4e131 to your computer and use it in GitHub Desktop.
Save mre/f9e8d31cd1bde76fc714cae3f9d4e131 to your computer and use it in GitHub Desktop.
Fizzbuzz in Rust
#![feature(generators)]
#![feature(generator_trait)]
use std::ops::{Generator, GeneratorState};
fn fizzbuzz_println(upto: u64) {
for i in 0..upto {
if i % 3 == 0 && i % 5 == 0 {
println!("FizzBuzz");
} else if i % 3 == 0 {
println!("Fizz");
} else if i % 5 == 0 {
println!("Buzz");
} else {
println!("{}", i);
}
}
}
fn fizzbuzz_ifelse(upto: u64) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
for i in 0..upto {
if i % 3 == 0 && i % 5 == 0 {
result.push("FizzBuzz".into());
} else if i % 3 == 0 {
result.push("Fizz".into());
} else if i % 5 == 0 {
result.push("Buzz".into());
} else {
result.push(i.to_string());
}
}
result
}
fn fizzbuzz_vec(upto: u64) -> Vec<String> {
let mut result: Vec<String> = Vec::new();
for i in 0..upto {
result.push(match (i % 3, i % 5) {
(0, 0) => "FizzBuzz".into(),
(0, _) => "Fizz".into(),
(_, 0) => "Buzz".into(),
(_, _) => i.to_string(),
})
}
result
}
fn main() {
let fizzbuzz = |upto: u64| {
move || for i in 0..upto {
yield match (i % 3, i % 5) {
(0, 0) => "FizzBuzz".into(),
(0, _) => "Fizz".into(),
(_, 0) => "Buzz".into(),
(_, _) => i.to_string(),
}
}
};
let mut output = fizzbuzz(100);
loop {
match output.resume() {
GeneratorState::Yielded(x) => println!("{}", x),
GeneratorState::Complete(()) => break,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment