Live data from Hacker News

Fizz Buzz without conditionals or booleans

evanhahn.com

41–50 of 72 posts

Re: Fizz Buzz without conditionals or booleans

#45
post #19

Earlier quoted context omitted.

There's a conditional, though?

Yeah this is weird. It's against the rules to speculate about whether a commenter read the article, but what about the title of the article?

I did, in fact, read the article. I've offered my subversive FizzBuzz as an alternative. It's not according to the article's rules, but it's definitely against the grain of the normal FizzBuzz.

Re: Fizz Buzz without conditionals or booleans

#46
The suckless approach

  #include 
  #include 
  #include 

  void fizzbuzz(int i) {
      uint32_t r3 = i % 3;
      uint32_t r5 = i % 5;
      uint32_t is_nonzero_3 = (r3 | -r3) >> 31;
      uint32_t is_nonzero_5 = (r5 | -r5) >> 31;
      uint32_t is_zero_3 = is_nonzero_3 ^ 1;
      uint32_t is_zero_5 = is_nonzero_5 ^ 1;
      uint32_t idx = (is_zero_5 > 31;
  }

  func_t actions_table[] = { run_loop, stop_loop };

  void run_loop_wrapper(int i) {
      fizzbuzz(i);
      int d = 99 - i;
      uint32_t is_neg = ((uint32_t)d) >> 31;
      actions_table[is_neg](i + 1);
  }

  int main() {
      actions_table[0] = run_loop_wrapper;
      run_loop_wrapper(1);
      return 0;
  }

Re: Fizz Buzz without conditionals or booleans

#47
3 lines of python, no imports.

  fizzbuzz = [None, None, "Fizz", None, "Buzz", "Fizz", None, None, "Fizz", "Buzz", None, "Fizz", None, None, "FizzBuzz"]

  for i in range(1,100):
    print(fizzbuzz[i % 15] or i)
Edit: I see I was a few hours late, and someone posted nearly the exact same solution. :(

Re: Fizz Buzz without conditionals or booleans

#48
Late to the party but here's a solution I worked out using roots of unity and cosines:

  from math import cos, pi
  for n in range(1, 101):
      print([n, 'Fizz', 'Buzz', 'FizzBuzz'][round((1 + 2 * cos(2 * pi * n / 3)) / 3 + 2 * (1 + 2 * cos(2 * pi * n / 5) + 2 * cos(4 * pi * n / 5)) / 5)])

Re: Fizz Buzz without conditionals or booleans

#49
Simple solution using modulo arithmetic and arrays. Relies on python shorthands that hides implicit branches for the number case though.

    def main():
      fizz_array = ["Fizz", "", ""]
      buzz_array = ["Buzz", "", "", "", ""]

      for n in range(1, 101):
        # Use modulo to index into arrays
        f = fizz_array[n % 3]
        b = buzz_array[n % 5]

        # Combine fizz and buzz
        result = f + b
    
        output = result + str(n)[len(result):]
    
        print(output)
    
    main()

I couldn't figure out this line and had to rely on AI for it.

    output = result + str(n)[len(result):]
Post reply on HN