LebGeeks

A community for technology geeks in Lebanon.

You are not logged in.

#1 September 27 2010

Joe
Member

Exercise - FizzBuzz

This one is a classic. It is an old timer that is sometimes asked in interviews. You'd be surprised by the number of people who cannot properly do this.
Do the exercise in the language you know the least, or one you have been willing to learn.

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".

Extra points are awarded for creativity and exotic languages.

Offline

#2 September 27 2010

Joe
Member

Re: Exercise - FizzBuzz

#include<stdio.h>
#include<stdlib.h>

void fizzBuzz (int count);

int main (int argc, char* argv[])
{
    fizzBuzz(100);
}

void fizzBuzz (int count)
{
    int i=0;

    for (i=0; i<count; i++)
    {
        if (i%3 == 0) { printf("Fizz"); }
        if (i%5 == 0) { printf("Buzz"); }
        if (i%3 != 0 && i%5 != 0) { printf ("%d",i); }

        printf("\n");
    }
}

Here's my C implementation. Obviously, it lacks creativity. Show us something good :)

Offline

#3 September 27 2010

Joe
Member

Re: Exercise - FizzBuzz

Playing with the ternary operator in Java.

public class FizzBuzz {
  public static void main(String[] args) {
    for (int i = 0; i<=100; i++ ) {
      System.out.println((0==i%3 && 0==i%5) ? "FizzBuzz" : 0==i%3 ? "Fizz" : 0==i%5 ? "Buzz" : String.valueOf(i));
    }
  }
}

Offline

#4 September 28 2010

saeidw
Member

Re: Exercise - FizzBuzz

Here's a solution in Scheme that's basically the same as the above. The difference is that I didn't use a looping construct, instead I defined a function within my function to do the iterations. Scheme optimizes tail recursive calls.

(define (fizzbuzz n)
 (define (fizz-iter counter maxc)
  (if (= 0 (remainder counter 3)) (display "fizz"))
  (if (= 0 (remainder counter 5)) (display "buzz"))
  (if (and (not (= 0 (remainder counter 3)))
           (not (= 0 (remainder counter 5))))
      (display counter))
      (newline)
  (if (< counter maxc) (fizz-iter (+ counter 1) maxc)))
 (fizz-iter 1 n))

(fizzbuzz 100)

I could have also used let instead of defining a function, but I'm sort of used to doing it that way.

Last edited by saeidw (September 28 2010)

Offline

#5 September 28 2010

rolf
Member

Re: Exercise - FizzBuzz

I forgot how to do modulus in PHP, so instead of looking it up I did something else.
If this could be transcribed in C, it'll probably be more efficient then rahmu's solution.

<?php

$mult3 = 3; // int
$mult5 = 5; // int

for ($i=0;$i<101;$i++) {
	$printed = false; // bool
	if ($i == $mult3) {
		print("Fizz");
		$printed = true;
		$mult3 += 3;
	}
	if ($i == $mult5) {
		print("Buzz");		
		$printed = true;
		$mult5 += 5;
	}
	if (!$printed) {
		print($i);
	}
	print("<br/>\n");
}

?>

Last edited by rolf (September 28 2010)

Offline

#6 September 28 2010

rolf
Member

Re: Exercise - FizzBuzz

Here's another version, just for the sake of variation (and dare I say, creativity?). Instead of generating everything in a big loop, I'm editing an array over several smaller loops.

<?php
$arr = array();

for ($i=0;$i<101;$i++) {
	$arr[$i] = $i;
}

for ($i=3;$i<101;$i+=3) {
	$arr[$i] = "Fizz";
}

for ($i=5;$i<101;$i+=5) {
	if ( $arr[$i] == "Fizz" ) {
		$arr[$i] .= "Buzz";
	} else {
		$arr[$i] = "Buzz";		
	}
}

print(implode("<br/>", $arr));
?>

PS: Sorry I missed the part about doing this in the language I know the least.

Last edited by rolf (September 28 2010)

Offline

#7 September 28 2010

xterm
Moderator

Re: Exercise - FizzBuzz

a twist in ruby.

mod3 = lambda { |n| n%3 == 0 }
mod5 = lambda { |n| n%5 == 0 }
mod35 = lambda { |n| mod3.call(n) && mod5.call(n)}

(1..100)
.map { |n| mod35.call(n) ? "FizzBuzz" : mod3.call(n) ? "Fizz" :	mod5.call(n) ? "Buzz" : n }
.reduce { |s,c| "#{s}\n#{c}" }

Offline

#8 September 29 2010

Zef
Member

Re: Exercise - FizzBuzz

@xterm, I think you're making it a bit more complicated than it needs to be! Going for the creativity points?

The great thing about Ruby is that it can be very readable and understandable just by looking at it. No need for extra complexity!

Here's my Ruby version:

1.upto 100 do |index|
  string = ''
  string << 'Fizz' if index % 3 == 0
  string << 'Buzz' if index % 5 == 0
  string = index if string.empty?
  puts string
end

You can also use this to get the remainder:

  string << 'Fizz' if index.remainder(3).zero?
  string << 'Buzz' if index.remainder(5).zero?

Offline

#9 September 29 2010

xterm
Moderator

Re: Exercise - FizzBuzz

Zef wrote:

@xterm, I think you're making it a bit more complicated than it needs to be! Going for the creativity points?

Ofcourse. Much more complicated than it needs to be.

in fact it be much cooler if we use a bit of MOP.

string << index.fizz << index.buzz << index

or perhaps

[index.fizz, index.buzz, index].join

Last edited by xterm (September 29 2010)

Offline

#10 October 7 2010

mesa177
Member

Re: Exercise - FizzBuzz

This code is written in Matlab:

for i = 1:100
    if(mod(i,3))
        if(mod(i,5))
            disp(num2str(i));
        else
            disp('Buzz');
        end
    elseif(mod(i,5))
        disp('Fizz');
    else
        disp('FizzBuzz');
    end
end

Offline

#11 April 18 2014

NuclearVision
Member

Re: Exercise - FizzBuzz

I'm learning C++. It seemed quiet interesting to resolve the forum's exercises using the language.

// FizzBuzz
#include <iostream>
using namespace std;
int main()
{ int n=0,used[50];
  while (n<100)
    {   n++;
        if (n%3!=0  and n%5!=0)
		    {cout<<n<<endl;
		    }
	if (n%3==0)
	{  if (n%5==0)
	    {  
	      cout<<n<<"fizzBuzz\n";
              used[n]=n;
	    }
	   else cout<<n<<"fizz\n";
	}
	if (n%5==0) 
         
	  {  if (used[n]!=n)
	      { cout<<n<<"Buzz\n";
	      }
	  }
	
    }
  return 0;
}

Last edited by NuclearVision (April 19 2014)

Offline

#12 April 18 2014

Adnan
Member

Re: Exercise - FizzBuzz

count = -1
for i in range(0,100):
	count = count + 1
	mult3 = float(count / 3.0)
	mult5 = float(count / 5.0)
	if (mult3).is_integer() and (mult5).is_integer() is True:
		print 'FizzBuzz'
	elif (mult3).is_integer() is True:
		print 'Fizz'
	elif (mult5).is_integer() is True:
		print 'Buzz'
	else:	
		print count

I'm learning this tender language called Python, I think this is made too easy (and maybe ugly). I would really love to get remarks to help me improve.

Offline

#13 April 18 2014

NuclearVision
Member

Re: Exercise - FizzBuzz

@adnan Actually python code could be  simplified. Unlike other languages making it less difficult to control your code/edit it.

for i in xrange(1,101):
   li=[]
   if i%3==0:
      if i%5==0:
        print str(i)+ "FIZZBUZZ"
        li.append(i)
      else:
        print str(i)+ "fizz"
   if i%5==0 and i not in li:
      print str(i)+ "buzz"

regarding your code, there are some issues; particularly the counting variable in a for loop you don't need to increment the iterator (count=count+1) in fact the for loop does it automatically (by 1 if unspecified); you can specify by doing for(start,stop,incremented value)
notice that the loop wont stop at the "stop" value but at stop-1.
also you could always use the % modulo operator to check if the division is total or not, instead of verifying integers which is a pain in the ass.
Don't underestimate python, it is really awesome.

Last edited by NuclearVision (April 18 2014)

Offline

#14 April 18 2014

Joe
Member

Re: Exercise - FizzBuzz

  • The variable count is useless. You already have another variable that takes each successive value from 0 to 99. Can you spot it?

  • Stylistically, it's completely useless to put parenthesis around a variable name. (mult3).is_integer() should be mult3.is_integer()

  • Do not check if a boolean "is True"!

  • You're creating floats and storing them in memory, when you don't really need this conversion.

  • There are function calls you make several times. Why not doing it once, and storing the result in memory?

Here's something already better:

for count in range(-1, 100):
    count += 1
    mult3 = float(count / 3.0).is_integer()
    mult5 = float(count / 5.0).is_integer()

    if mult3 and mult5:
        print "FizzBuzz"
    elif mult3:
        print "Fizz"
    elif mult5:
        print "Buzz"
    else:
        print count

Note that mult3 and mult5 are now storing boolean values. And note that the "if" statements aren't checking agains "is True". We can further improve this, by avoiding the conversion to float:

for count in range(-1, 100):
    count += 1

    # The "%" operator returns the remainder of an integer division.
    # Note that the parens are optional, I just added them for readability.
    mult3 = (count % 3 == 0)
    mult5 = (count % 5 == 0)

    if mult3 and mult5:
        print "FizzBuzz"
    elif mult3:
        print "Fizz"
    elif mult5:
        print "Buzz"
    else:
        print count

Offline

#15 April 18 2014

Adnan
Member

Re: Exercise - FizzBuzz

Thanks for your help !

@NuclearVision the problem with your piece of code is that it doesn't exactly answer the question, but I will try to work on it and submit it soon, I should work on better understanding lists.

Offline

#16 April 19 2014

NuclearVision
Member

Re: Exercise - FizzBuzz

for i in xrange(1,101):
   if i%3!=0 and i%5!=0: print str(i)
      
   li=[]
   if i%3==0:
      if i%5==0: print str(i)+ "FIZZBUZZ";li.append(i);
   else:  print str(i)+ "fizz"        
   if i%5==0 and i not in li: print str(i)+ "buzz"
      

Better? actually i didn't quiet focus on the question, thanks for pointing it out. Will be editing my C++ code.

Last edited by NuclearVision (April 19 2014)

Offline

#17 April 19 2014

Adnan
Member

Re: Exercise - FizzBuzz

Better, but not correct yet !

You can see that from the output: http://pastebin.com/5jhut4Bz
I tried to work around your code and came up with this which gives the correct output:

li=[]
for i in xrange(0,101):
        if i%3!=0 and i%5!=0:
                print str(i)
        elif i%3==0 and i%5==0:
                print 'FizzBuzz'
                li.append(i)
        elif i%3==0:
                print 'Fizz'
                li.append(i)
        if i%5==0 and i not in li:
                print 'Buzz'

PS: Don't forget the zero.

Last edited by Adnan (April 19 2014)

Offline

#18 April 19 2014

NuclearVision
Member

Re: Exercise - FizzBuzz

for i in xrange(1,101):
   if i%3!=0 and i%5!=0:
      print str(i)
   li=[]
   if i%3==0:
      if i%5==0:
        print str(i)+ "FIZZBUZZ"
        li.append(i)
      else:
        print str(i)+ "fizz"
   if i%5==0 and i not in li:
      print str(i)+ "buzz"

Sorry adnan again my fault, i was getting the wanted output because emacs was compiling my c++ code instead (same name).
ps: 0 is not wanted :]

Offline

#19 April 19 2014

Adnan
Member

Re: Exercise - FizzBuzz

Ah, crap. Didn't notice. Great, all shiny now !

Offline

#20 April 19 2014

venam
Member

Re: Exercise - FizzBuzz

--

Last edited by venam (September 9 2016)

Offline

#21 April 19 2014

NuclearVision
Member

Re: Exercise - FizzBuzz

for i in [ "fizz" if i%3==0 and i%5!=0 else " buzz" if i%5==0 and i%3!=0 else "fizzbuzz" if i%3==0 and i%5==0 else str(i) for i in xrange(1,101)]: print i
  

I thought I'd share this one liner.

Last edited by NuclearVision (July 19 2015)

Offline

#22 February 18 2016

Joe
Member

Re: Exercise - FizzBuzz

In Go:

package main

import (
	"fmt"
	"strconv"
)

func fizzbuzz(n int) string {
	var result string
	for i := 0; i <= n; i++ {
		if i%3 == 0 && i%5 == 0 {
			result = "fizzbuzz"
		} else if i%3 == 0 {
			result = "fizz"
		} else if i%5 == 0 {
			result = "buzz"
		} else {
			result = strconv.Itoa(i)
		}
		fmt.Printf("%s\n", result)
	}
	return result
}

func main() {
	fizzbuzz(20)
}

Offline

#23 February 18 2016

rolf
Member

Re: Exercise - FizzBuzz

Since we're reviving this thread, I had to try myself at this problem again.
Here's a horrible one-liner, with a more functional approach (no variables are muted), in JavaScript:

console.log((new Array(100)).join(0).split('').map(function(v,i){return(((i+1)%3==0)&&((i+1)%5==0)?"FizzBuzz":((i+1)%3==0)?"Fizz":((i+1)%5==0)?"Buzz":(i+1));}).join("\n"));

Since Array.map() would ignore undefined values, I have to do join() then split() to end up with an array of zeroes (or anything else than undefined). Anyone knows a better way of doing it in javascript?

Last edited by rolf (March 2 2016)

Offline

Board footer