Fizz Buzz

Pages: 123
This man's solution to the fizzbuzz interview question is magnificent.
http://www.adampetersen.se/articles/fizzbuzz.htm#!___Last_submitted_5_years_ago

Also, feel free to post your own :'D

“Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.”
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import std.stdio;

void main()
{
    foreach (n; 1 .. 101)
        if (n % 15 == 0)
            writeln("FizzBuzz");
        else
        if (n % 5 == 0)
            writeln("Buzz");
        else
        if (n % 3 == 0)
            writeln("Fizz");
        else
            writeln(n);
}


I guess I'm too dumb to take advantage of the similarities between "FizzBuzz" and "Fizz" and "Buzz", thereby trying to simplify the code by complicating it.
Last edited on
Here are my two favourite ones:
1. http://pastebin.com/CZEjqVj6
2. http://pastebin.com/VUpfZ9az

[edit]:
@Catfish,
What language is that?
Last edited on
@Chrisname

It's D
Wow I suck. I tried it in Smalltalk, but I really couldn't do better than that.

1
2
3
4
5
6
7
8
9
10
1 to: 100 do: [ :num |
	| fizz buzz s|
	s:= ''.
	fizz := (num rem: 3) = 0.
	buzz := (num rem: 5) = 0.
	fizz ifTrue: [s := s,'Fizz'].
	buzz ifTrue: [s := s,'Buzz'].
	(fizz or: buzz) ifFalse: [s := s, num asString].
	Transcript show: s ; cr.
	]


I'm sure there's a much less naive solution than that (it ended up looking almost identical to the C version).
closed account (1yR4jE8b)
I like this thread, getting to see different languages/solutions to the same problem.

Here's Ruby:

1
2
3
4
5
6
7
8
9
10
11
12
13
(1..100).each { |i|
  divd = false
  if(i % 3 == 0)
    print "Fizz"
    divd = true
  end
  if(i % 5 == 0)
    print "Buzz"
    divd = true
  end
  print i if not divd
  puts
}

Perl!

1
2
3
4
5
6
foreach(1..100) {
    print "Fizz" unless $_ % 3;
    print "Buzz" unless $_ % 5;
    print $_ if $_ % 3 && $_ % 5;
    print "\n";
}


EDIT: Nah, I can do better than that.
print+("Fizz")[$_%3].("Buzz")[$_%5]||$_,"\n" for 1..100;
It's a one-liner now. I added in some "" because the (string) syntax (as a C++ programmer) bugs me.

-Albatross
Last edited on
Hm... Haskell? (Is it cheating if I do it twice?)

1
2
3
4
5
6
7
main = putStrLn fizzBuzz
  where fizzBuzz = concat $ zipLists (++) (repeat "\n" : map ($[1..100]) [fizz,buzz,nums])
        fizz = map $ cond ((==0). (`mod`3)) (\_->"Fizz") ""
        buzz = map $ cond ((==0). (`mod`5)) (\_->"Buzz") ""
        nums = map $ cond (not .flip any [(==0). (`mod`3),(==0). (`mod`5)] . (flip ($))) show ""
        zipLists f = foldr1 $ zipWith f
        cond p f s x = if p x then f x else s


(Bonus points if you can read that without prior Haskell exposure).

Again, could probably be done shorter, but this was the first thing I could think of. And it looks almost cryptic enough to me, so I'll let it pass.

EDIT: Didn't actually manage to get it short, but I DID succeed in making it less readable.
Last edited on
Obvious haskell : http://ideone.com/ozCJS
Silly haskell : http://ideone.com/fGeVv
Sillier haskell : http://ideone.com/svzoq
Oh please, that first one makes way too much sense.
1
2
3
4
5
6
7
#include <iostream>
using namespace std ;
ostream & c = cout ;
int main()
{
	for ( unsigned i=1, f; i<= 100 && ((f = false) || ( (i%3 || (f=!!(c << "Fizz")))  &&  (i%5 || (f=!!(c <<"Buzz"))) && (!f && c << i) || f) && c << '\n') ; ++i ) ;
}


=P
Last edited on
Scheme:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(define (Divides A B)
   (= (modulo B A) 0) )

(define (fizz-buzz current finish)
   (if (<= current finish)
       (begin
          (cond ( (and (Divides 3 current) (Divides 5 current)) (display "FizzBuzz") )
                ( (Divides 3 current) (display "Fizz") )
                ( (Divides 5 current) (display "Buzz") )
                ( else (display current) ))
          (newline)
          (fizz-buzz (+ current 1) finish))
       (display "")))

(fizz-buzz 1 100)
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
drunk(X, 'FizzBuzz') :- 0 is X mod 3, 0 is X mod 5, !.
drunk(X, 'Fizz') :- 0 is X mod 3, !.
drunk(X, 'Buzz') :- 0 is X mod 5, !.
drunk(X, X).

fizzbuzz(N) :-
	drunk(N, Result),
	write(Result), nl.

%It seems that there is no between in gprolog
loop(Finish, Finish, _) :- !.
loop(Start, Finish, Action):- 
	call(Action, Start),
	Next is Start+1,
	loop(Next, Finish, Action).

%the query
loop(1,101,fizzbuzz).
1
2
3
4
5
6
1 to 100 map { 
  case x if x % 15 == 0 => "FizzBuzz"; 
  case x if x % 5 == 0 => "Buzz";  
  case x if x % 3 == 0 => "Fizz"; 
  case x => x 
} foreach println
Here's a python one-liner:

for n in range(1, 101) : print (n, "Fizz", "Buzz", "FizzBuzz")[(n % 3 == 0) + 2 * (n % 5 == 0)]
Now, let's do it in a scalable way:

http://ideone.com/8ySTr (python)
http://ideone.com/Z6KWy (haskell)
http://ideone.com/Nrvzy (haskell)

EDIT:

*looks at Catfish's code below* Damn... Why didn't I think of that?...
*edits ideone paste quickly, hoping that nobody else has noticed...*

EDIT2: Added a haskell solution.
EDIT3: Added another haskell solution.
Last edited on
Thanks for the inspiration, r0shi.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import std.array;
import std.conv;
import std.stdio;

void main()
{
    immutable auto dictionary = ["Fuzz":2, "Fizz":3, "Buzz":5, "Bizz":7];

    foreach (n; 1 .. 101)
    {
        string output;

        foreach (w; dictionary.byKey)
            if (n % dictionary[w] == 0)
                output ~= w; // concatenation

        if (output.empty)
            output = to!string(n);

        writeln(output);
    }
}


Edit: ~= operator clarification.
Last edited on
An unobfuscated, scalable Haskell version. Just for sake of completeness.

http://ideone.com/qYFu8
That was nice. I would need at least a week to come up with something like that.

I think I need more practice in functional thinking...
Last edited on
Hi all.
I have an overkilling solution in C++11

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <type_traits>

template <class N=int>
    class basic_range
{
    public:
        typedef N number_type;

        static_assert ( std::is_integral<number_type>::value ||
                       std::is_floating_point<number_type>::value,
                       "basic_range is only for numeric types" );

        class iterator
        {
            private:
                basic_range r;
                number_type current;
                friend class basic_range;
                iterator ( basic_range r, number_type current ) :
                    r ( r ), current ( current ) {}
            public:

                iterator() : iterator ( {0,0}, 0, 0 ) {}

                N operator* () const { return current; }
                operator N () const { return current; }

                iterator& operator+= ( int n )
                {
                    current += n*r.step();
                    if ( current > r.last() )
                        current = r.last();
                    return *this;
                }
                iterator& operator-= ( int n )
                {
                    current -= n*r.step();
                    if ( current < r.first() )
                        current = r.last();
                    return *this;
                }
                iterator& operator++ ()
                {
                    return *this += 1;
                }
                iterator& operator-- ()
                {
                    return *this -= 1;
                }
                iterator operator++ (int)
                {
                    iterator copy;
                    *this += 1;
                    return copy;
                }
                iterator operator-- (int)
                {
                    iterator copy;
                    *this -= 1;
                    return copy;
                }

        };

    protected:
        number_type nbegin, nend, nstep;

    public:

        basic_range ( number_type begin, number_type end, number_type step = 1 )
            : nbegin ( begin < end ? begin : end ),
              nend ( begin < end ? end : begin ),
              nstep ( step ) {}

        number_type first() const { return nbegin; }
        number_type last() const { return nend; }
        number_type step() const { return nstep; }
        void first ( number_type n ) const { nbegin = n; }
        void last ( number_type n ) const { nend = n; }
        void step ( number_type n ) const { nstep = n; }

        iterator begin () const
        {
            return iterator(*this,nbegin);
        }
        iterator end () const
        {
            return iterator(*this,nend);
        }
        iterator rbegin () const
        {
            return iterator(basic_range(nbegin,nend,-std::make_signed<number_type>(step)),nend);
        }
        iterator rend () const
        {
            return iterator(basic_range(nbegin,nend,-std::make_signed<number_type>(step)),nbegin);
        }
};

template < class N >
    basic_range<N> range ( N begin, N end, N step = 1 )
    {
        return basic_range<N>(begin,end,step);
    }


template<class charT=char,class Traits=std::char_traits<charT>,class Numb=unsigned>
    class basic_buzzer
{
    static_assert ( std::is_integral<Numb>::value,
                   "basic_buzzer is only for integral types" );
public:
    typedef std::map<unsigned,std::basic_string<charT,Traits>> map_type;
    typedef basic_range<Numb> range_type;
protected:
    range_type range;
    std::map<unsigned,std::basic_string<charT,Traits>> buzz;

public:

    basic_buzzer ( range_type range, std::map<unsigned,std::string> buzz )
        : range(range), buzz(buzz) {}

    basic_buzzer ( unsigned min, unsigned max, std::map<unsigned,std::string> buzz )
        : basic_buzzer({min,max},buzz) {}

    basic_buzzer ( unsigned min, unsigned max )
        : basic_buzzer(min, max, {{3,"Fizz"},{5,"Buzz"}}) {}

    basic_buzzer ( unsigned max, std::map<unsigned,std::string> buzz )
        : basic_buzzer(1, max, buzz) {}

    basic_buzzer ()
        : basic_buzzer(1, 100) {}


    friend std::basic_ostream<charT,Traits>& operator<< (
                             std::basic_ostream<charT,Traits>& out,
                             const basic_buzzer& buzz )
    {
        for ( auto i : buzz.range )
        {
            std::basic_string<charT,Traits> bzz;
            for ( const auto& p : buzz.buzz )
                if ( ( i % p.first ) == 0 )
                    bzz += p.second;
            if ( bzz.empty() )
                out << i << std::endl;
            else
                out << bzz << std::endl;
        }
        return out;
    }
};

typedef basic_buzzer<char> buzzer;

buzzer operator "" _buzz ( unsigned long long n )
{
    return buzzer ( 1, n );
}

buzzer operator "" _buzz ( const char* str, long unsigned sz )
{
    std::istringstream ss ( std::string(str,sz) );
    unsigned start = 1;
    unsigned end = 1;
    char la =';';

    ss >> start >> la;
    if ( la == '-' )
    {
        ss >> end >> la;
    }
    else
        std::swap ( start, end );

    if ( la == ';' )
    {
        buzzer::map_type map;
        std::pair<unsigned,std::string> p;
        while ( true )
        {
            ss >> p.first >> la;
            if ( !ss || la != ':' )
                break;
            getline(ss,p.second,',');
            map.insert(p);
        }
        return buzzer ( start, end, map );
    }

    return buzzer ( start, end );
}


int main()
{
    std::cout << "1-100;3:Fizz,5:Buzz"_buzz;
    return 0;
}
Last edited on
Pages: 123