@Pravesh,
The idea is usually to find the shortest solution, but it's much more fun to write a ridiculous one (one of mine uses a client/server architecture, for example).
Since everyone's getting crazy with languages, here's my old favorite:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
: Fizz? ( n -- b )
3 mod 0= dup if ." Fizz" then
;
: Buzz? ( n -- b )
5 mod 0= dup if ." Buzz" then
;
: main ( -- )
101 1 do
i Fizz? i Buzz? or invert if i . then cr loop
;
main
I'm amazed at the number of links to code on ideone.com that show incorrect output.
Which one are you talking about? I didn't check all of them, but I've only seen correct solutions so far (although half the solutions on the last page were for FizzFuzzBuzzBizz rather than FizzBuzz).
Sorry to ressurect a month-old thread, but here's a solution using list comprehensions in Haskell.
1 2 3 4 5 6 7 8
let fizzbuzz n = [ fb |
x <- [1 .. n],
fb <- [ f ++ b |
f <- [if x `mod` 3 == 0 then "fizz"else""],
b <- [if x `mod` 5 == 0 then "buzz"else""],
f <- [if (f == "") && (b == "") then show x else f]
]
]
(paste into GHCi and then call fizzbuzz with a number).
(define fizz-buzz
(lambda (n set)
(if (< n 1) set
(cond ((= (mod n 15) 0) (fizz-buzz (- n 1) (append set 'fizzbuzz)))
((= (mod n 5) 0) (fizz-buzz (- n 1) (append set 'buzz)))
((= (mod n 3) 0) (fizz-buzz (- n 1) (append set 'fizz)))
(else (fizz-buzz (- n 1) (append set n)))))))
(fizz-buzz 100 '())
Just started learning scheme. I feel I'm doing ok.
I'm not a big fan of using monad syntax for Lists though. Oh well, while we're at it...
common lisp:
1 2 3 4 5 6 7
(format t "~{~a~%~}~%"
(loop for i from 1 to 100 collecting
(let ((fizz (= 0 (mod i 3))) (buzz (= 0 (mod i 5))))
(concatenate 'string
(when fizz "Fizz")
(when buzz "Buzz")
(unless (or fizz buzz) (write-to-string i))))))
Or, more general:
1 2 3 4 5 6 7 8
(defmacro fizzer (begin end &rest list)
`(loop for i from ,begin to ,end collecting
(concatenate 'string
,@(loop for (num name) in list collecting
`(when (= 0 (mod i ,num)) ,name))
(unless (or ,@(loop for (num _) in list collecting
`(= 0 (mod i ,num))))
(write-to-string i)))))
Which can be called like this:
(format t "~{~a~%~}~%" (fizzer 1 100 (3 "Fizz") (5 "Buzz")))
Please mind that I am pretty new to CL so I might have made that last part a tad bit more complicated that it needed to be.
EDIT: Fixed calls so it actually prints the results. Forgot that was part of the task.
EDIT2: There's a caveat to the macro solution - it assumes that the values passed for the fizz/buzz pairs are literals. If you use function calls with side effects there it might not work (depending on what those side effects are). I could fix this, but that would be even less readable and the macro probably wouldn't be used that way anyways.