Toy problem - Obfuscating Fizz buzz

Hello! I have a fun challenge, and I want to see if it is possible to improve my solution. Instead of making a clean an idiomatic program, I want to try to solve the Fizz buzz problem as confusingly as possible. (Why? Because I thought it would be funny.) My current best implementation uses the short-circuiting nature of &&, but I'm wondering if it is possible to push the challenge any further.

Playground link

const MAX: usize = 20;

fn basic() {
    for i in 1..=MAX {
        if i % 15 == 0 {
            println!("fizzbuzz");
        } else if i % 3 == 0 {
            println!("fizz");
        } else if i % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", i);
        }
    }
}

fn complex() {
    for i in 1..=MAX {
        if (i % 15 == 0 && println!("fizzbuzz") == ())
            || (i % 3 == 0 && println!("fizz") == ())
            || (i % 5 == 0 && println!("buzz") == ())
            || println!("{i}") == () {}
    }
}

fn obfuscated() {
    for i in 1..=MAX {
        if !(i%15==0&&println!("fizzbuzz")==()||i%3==0&&println!("fizz")==()||i%5==0&&println!("buzz")==()) {
            println!("{i}");
        }
    }
}

fn main() {
    obfuscated();
}

Any attempts / suggestions are appreciated!

1 Like

You could change your if-statement into a single expression and use Iterator methods rather than a for-loop:

const MAX: usize = 20;

fn obfuscated() {
    (1..=MAX)
        .map(|i| {
            (i % 15 == 0 && println!("fizzbuzz") == ()
                || i % 3 == 0 && println!("fizz") == ()
                || i % 5 == 0 && println!("buzz") == ()
                || println!("{i}") == ())
                .then_some(())
        })
        .collect::<Option<()>>()
        .unwrap();
}

fn main() {
    obfuscated();
}

Playground.

3 Likes

There's no limit to questions like that (no rust answer but you get the idea)

4 Likes

Fun with traits and Option combinators.

3 Likes

Please allow me to add an enhanced version, which is:

  • more idiomatic (to assembly programmers);
  • more performant (tightly bit-packed);
  • easily readable (at least the output).

Here it is.

FAQ

  1. Q: "I don't understand how this works!"
    A: Thanks!
17 Likes