Last active
January 25, 2019 23:54
-
-
Save lholden/7107811 to your computer and use it in GitHub Desktop.
Random FizzBuzz implementations of mine.I've contributed each version to: http://rosettacode.org/wiki/FizzBuzz
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
Haskell: | |
------- | |
fizzBuzz :: (Integral a) => a -> String | |
fizzBuzz i | |
| fizz && buzz = "FizzBuzz" | |
| fizz = "Fizz" | |
| buzz = "Buzz" | |
| otherwise = show i | |
where fizz = i `mod` 3 == 0 | |
buzz = i `mod` 5 == 0 | |
main = mapM_ (putStrLn . fizzBuzz) [1..100] | |
------- | |
Ruby | |
------- | |
fizzbuzz = ->(i) do | |
(i%15).zero? and next "FizzBuzz" | |
(i%3).zero? and next "Fizz" | |
(i%5).zero? and next "Buzz" | |
i | |
end | |
puts (1..100).map(&fizzbuzz).join("\n") | |
------- | |
C++11 | |
------- | |
int main() | |
{ | |
std::vector<int> range(100); | |
std::iota(range.begin(), range.end(), 1); | |
std::vector<std::string> values; | |
values.resize(range.size()); | |
auto fizzbuzz = [](int i) -> std::string { | |
if ((i%15) == 0) return "FizzBuzz"; | |
if ((i%5) == 0) return "Buzz"; | |
if ((i%3) == 0) return "Fizz"; | |
return std::to_string(i); | |
}; | |
std::transform(range.begin(), range.end(), values.begin(), fizzbuzz); | |
for (auto& str: values) std::cout << str << std::endl; | |
return 0; | |
} | |
------- | |
Rust | |
------- | |
fn fizzbuzz(n: u32) -> String { | |
match (n % 3 == 0, n % 5 == 0) { | |
(true, true) => "fizzbuzz".into(), | |
(true, false) => "fizz".into(), | |
(false, true) => "buzz".into(), | |
(false, false) => n.to_string(), | |
} | |
} | |
struct FizzBuzz { | |
next: u32, | |
max: u32, | |
} | |
impl FizzBuzz { | |
fn new(start: u32, length: u32) -> Self { | |
let max = if length > 0 { start + length - 1 } else { 0 }; | |
FizzBuzz { next: start, max } | |
} | |
} | |
impl Iterator for FizzBuzz { | |
type Item = String; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.next > self.max { return None } | |
let msg = fizzbuzz(self.next); | |
self.next += 1; | |
Some(msg) | |
} | |
} | |
fn main() { | |
let output = FizzBuzz::new(1, 100) | |
.collect::<Vec<String>>() | |
.join("\n"); | |
println!("{}", output); | |
} | |
------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment