Hacker News new | ask | show | jobs
by seanjensengrey 4455 days ago
https://gist.github.com/seanjensengrey/d053e7fa709e0699e291

If free version.

    t = {}
    t[0,0] = lambda x: x
    t[1,0] = lambda x: "Fizz"
    t[0,1] = lambda x: "Buzz"
    t[1,1] = lambda x: "FizzBuzz"
    
    def tests(x):
        return (x % 3 == 0, x % 5 == 0)
    
    for x in range(1,101):
        print t[tests(x)](x)
1 comments

Good idea. Enhancing:

If, lambda, logical operators except == and string concatenation free version (Python 3)

    for x in range( 1, 101 ):
        print( [ x,'Buzz','Fizz','FizzBuzz' ][ (x%3==0)*2 + (x%5==0) ] )
And also C based on the same idea as my Python (but this has to ? for 0s):

    int i;
    char* a[] = { 0, "Buzz", "Fizz", "FizzBuzz" };
    char* f[] = { "%s\n", "%d\n" };
    for ( i = 1; i < 101; i++ ) {
        char* s = a[ (i%3==0)*2 + (i%5==0) ];
        printf( f[!s], s ? s : i );
    }
Don't ruin that version with an if statement.

Use this and avoid it( and the second array as well ):

  char * a[] = { "%d\n" , "Fizz\n" , "Buzz\n" , "FizzBuzz\n" } ;
Brilliant, thanks! The C version is now:

    int i; char* a[] = { "%d\n", "Fizz\n", "Buzz\n", "FizzBuzz\n" };
    for ( i = 1; i < 101; i++ )
        printf( a[ (i%5==0)*2 + (i%3==0) ], i );