DEV Community

Discussion on: Taking a Look at an Odd FizzBuzz Solution

Collapse
 
louy2 profile image
Yufan Lou • Edited

Tried to apply the same bit pattern tech in Rust, but Rust requires the template string to be a literal. The end result is kinda weird:

fn fizzbuzz(n: usize) {
    use std::borrow::Cow;
    const A: [Cow<str>; 3] = [
        Cow::Borrowed("FizzBuzz"),
        Cow::Borrowed("Buzz"),
        Cow::Borrowed("Fizz"),
    ];
    for i in 1..=n {
        let j: usize = !(0x1241843 >> ((i % 15) * 2)) & 0b11;
        println!("{}", A.get(j).unwrap_or(&i.to_string().into()));
    }
}

fn main() {
    fizzbuzz(50);
}

Playground