Created
December 31, 2021 01:05
-
-
Save fauve-/8d52b49319d8818072ee34f72761df27 to your computer and use it in GitHub Desktop.
Let's get deranged
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
[package] | |
name = "ultrabuzz" | |
version = "0.1.0" | |
edition = "2021" | |
[dependencies] | |
num = "0.4" |
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
use num::Num; | |
trait Fizzbuzz { | |
fn fizz(&self) -> bool; | |
fn buzz(&self) -> bool; | |
fn fizzbuzz(&self) -> bool; | |
} | |
// Yes, copy is cheating | |
impl<T: Num + Copy> Fizzbuzz for T { | |
fn fizz(&self) -> bool { | |
let three = if let Ok(t) = <T as Num>::from_str_radix("3", 10) { | |
t | |
} else { | |
panic!("what is three"); | |
}; | |
self.rem(three) == num::zero() | |
} | |
fn buzz(&self) -> bool { | |
let five = if let Ok(t) = <T as Num>::from_str_radix("5", 10) { | |
t | |
} else { | |
panic!("we have made a terrible mistake"); | |
}; | |
self.rem(five) == num::zero() | |
} | |
fn fizzbuzz(&self) -> bool { | |
let fifteen = if let Ok(t) = <T as Num>::from_str_radix("15", 10) { | |
t | |
} else { | |
panic!("seriously, numbers are broken?") | |
}; | |
self.rem(fifteen) == num::zero() | |
} | |
} | |
fn fizzbuzz_one<T: Num + std::fmt::Debug + Copy>(number: T) -> String { | |
if number.fizzbuzz() { | |
"fizzbuzz".to_string() | |
} else if number.fizz() { | |
"fizz".to_string() | |
} else if number.buzz() { | |
"buzz".to_string() | |
} else { | |
format!("{:?}", number) | |
} | |
} | |
fn fizzbuzz_range(lo: usize, hi: usize) -> Vec<String> { | |
(lo..hi).map(|n| fizzbuzz_one(n)).collect() | |
} | |
fn main() { | |
println!("On a float {}", fizzbuzz_one(15.0)); | |
println!("On an int {}", fizzbuzz_one(3)); | |
println!("On a range:"); | |
fizzbuzz_range(1, 16) | |
.iter() | |
.for_each(|buzzed| println!("{}", buzzed)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment