Re:FizzBuzz solved using only bit twiddling
by tylerkahn on Monday October 28, 2013 @02:57PM
(#6629034)
[ Parent
| on HN ]
Re:FizzBuzz solved using only bit twiddling
by GyrosOfWar on Monday October 28, 2013 @03:17PM
(#6629146)
Very cool. This really makes me want to get better at Haskell. I know enough of it to understand what's going on here, but not enough to be able to come up with something like this.
I love this answer. It's like "yes I know and hate fizzbuzz, also you don't know crap", but in code.
Poetry.
In python:
from itertools import *
fizz = cycle(["", "", "fizz"])
buzz = cycle([""] * 4 + ["buzz"])
fizzbuzz = izip(fizz, buzz, xrange(1,100))
print "\n".join(map(lambda (x,y,z): x+y if x or y else str(z), fizzbuzz))
(bugs found by marekmroz fixed)Can you do [1,2,3] * 4 in haskell as well ?
Re:FizzBuzz solved using only bit twiddling
by marekmroz on Monday October 28, 2013 @04:00PM
(#6629372)
Funny thing is, as soon as I saw OP's solution I fired up IPython to do the same thing in Python. :)
Admittedly mine was not as elegant as I haven't thought of using izip with 3 iterables. Still, I don't think that lambda and islice is really needed... xrange(100) guarantees a finite number of iterations already.
from itertools import *
fizzer = cycle(['Fizz','',''])
buzzer = cycle(['Buzz','','','',''])
fizzbuzzer = izip(xrange(100), fizzer, buzzer)
for f in fizzbuzzer:
print f[1] + f[2] if f[1] or f[2] else f[0]
EDIT:
the output from your version does not look right. "Fizz" and "Buzz" are on the wrong index positions.
0
1
fizz
3
buzz
fizz
6
7
fizz
buzz
...heh you're right. Now I feel so dumb. Off by one error. I needed to use xrange(1, 100) instead of just xrange.
You're also correct islice is not needed.
Re:FizzBuzz solved using only bit twiddling
by gamegoblin on Monday October 28, 2013 @04:00PM
(#6629374)
I more gray-bearded haskell wizard than I might have a better solution, but to me the direct haskell equivalent of python's [1,2,3]*4 is
concat $ replicate 4 [1,2,3]