Jump to content


FizzBuzz - Simple Programming Exercise


49 replies to this topic

#1 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 25 January 2007 - 12:22 PM

Assalamulaikum,

Baru terbaca article ni: http://tickletux.wordpress.com/2007/01/24/...who-grok-coding
Tentang soalan interview, utk write satu code simple mengikut permainan budak2 FizzBuzz.
QUOTE
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”

Tulis satu program yang akan memaparkan nombor-nombor 1 hingga 100. Jika nombor tersebut ialah gandaan 3, jangan paparkan nombor itu, tapi paparkan "Fizz". Jika gandaan 5, paparkan "Buzz". Jika ia gandaan sepunya bagi 3 dan 5, paparkan "FizzBuzz"


Jadi, nak ajak kawan2 buat dan pastekan code kat sini. Apa2 language pun boleh.

Objective:
- Uji diri sendiri, berapa lama utk fikirkan algorithmnya.
- Siapa boleh buat algo yang lebih elegant dari yg lain. Seperti, tak guna looping biasa, gunakan numerical methods ke apa ke.
- Nak tengok syntax dari pelbagai language.
- Digalakkan betulkan code orang lain (improve), tuan punya code jgn kecik hati pulak.

Semua dijemput hadir. So marilah para coder C, C++, C#, Java, D, JavaScript/VBScript, VB/Basic, Perl, PHP, Python, Ruby, Pascal/Delphi, shell/batch script, ActionScript, Cobol, Fortran, Lisp, Scheme, OCaml, F#, Smalltalk, Erlang, XSL, Assembly pun ok...

Nak guna language pelik2 mcm Whitespace atau Brainf*ck pun buleh biggrin.gif Pakai HTML pun takpe ph34r.gif

Edited by 1kHz, 25 January 2007 - 12:28 PM.


#2 Helmi 0mar

    Leftenan Muda

  • Ahli Professional
  • 553 posts
  • Gender:Male
  • Location:shah alam
  • Interests:tgk tv
  • Kepakaran:ym
  • Freelance:Tidak

Posted 25 January 2007 - 01:41 PM

tak de org reply lg ke..? meh aku try guna basic flow guna python v2.3.3.. spatutnya bleh bg simple lg kut.. aku fikir flow ni lama gak nih.. otak dah berkarat.. haha biggrin.gif feel free to improve it..

CODE
for idx in range(1,101):
  if not idx%(3*5):
    print 'fizzbuzz'
  elif not idx%3:
    print 'fizz'
  elif not idx%5:
    print 'buzz'
  else:
    print idx


#3 amry

    Kapten

  • Core
  • 2,178 posts
  • Gender:Male
  • Location:Wangsa Maju
  • Kepakaran:Programming
  • Freelance:Tidak

Posted 25 January 2007 - 01:46 PM

[ C# ]

CODE
using System;

namespace FizzBuzzApp
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++) {
                bool multiple3 = ((i%3) == 0);
                bool multiple5 = ((i%5) == 0);
                
                if (!multiple3 && !multiple5) {
                    Console.Write(i);
                }
                
                if (multiple3) {
                    Console.Write("Fizz");
                }
                
                if (multiple5) {
                    Console.Write("Buzz");
                }
                
                Console.WriteLine();
            }
        }
    }
}


#4 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 25 January 2007 - 02:33 PM

PHP
CODE
for( $i=1;$i<=100;$i++ )
{
echo (($i % 3 == 0) and ($i % 5 == 0)) ? "FizzBuzz<br/>" :
(($i % 3 == 0) ? "Fizz<br/>" :
(($i % 5 == 0) ? "Buzz<br/>" : $i . "<br/>"));
}


#5 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 25 January 2007 - 02:34 PM

Oleh sbb aku tgh gian dgn Ruby, aku post Ruby punya script.

CODE
1.upto 100 do |i|
    div3 = (i % 3 == 0)
    div5 = (i % 5 == 0)
    
    if !div3 and !div5
        print i
    else
        print 'Fizz' if div3
        print 'Buzz' if div5
    end
    puts ''
end


Menarik.. menarik.. mari kita kasi meriah lagi. Perl scripters, nak tengok Perl's one-liner.. boleh ke utk ni?

p.s: Kebetulan, algo sama dgn amry punya

#6 einiaz

    Kadet

  • Ahli
  • 8 posts
  • Gender:Male
  • Location:Kuala Lumpur
  • Kepakaran:embedded system, C programming
  • Freelance:Ya

Posted 25 January 2007 - 02:50 PM

aku cuma reti C jek ...

CODE
#include <stdio.h>

main( )
{
int i = 0;

while( i != 100 )
{
++i;
if( ( ( i % 3 ) == 0 ) && ( ( i % 5 ) == 0 ) )
{
printf( "FizzBuzz\n" );
}
else
if( ( i % 3 ) == 0 )
{
printf( "Fizz\n" );
}
else
if( ( i % 5 ) == 0 )
{
printf( "Buzz\n" );
}
else
{
printf( "%d\n", i );
}
}
}


#7 k4ml

    Leftenan Muda

  • Ahli Professional
  • 834 posts
  • Location:KB
  • Kepakaran:Linux, Freebsd, PHP, Drupal, PostgreSQL
  • Freelance:Ya

Posted 25 January 2007 - 04:38 PM

CODE

select case
when num % 3 = 0 AND num % 5 = 0 then 'FizzBuzz'
when num % 3 = 0 then 'Fizz'
when num % 5 = 0 then 'Buzz'
else num::varchar
end from generate_series(1,101) as num;

tested on postgresql 8.0.3 tapi tak best sangat sebab condition utk 'FizzBuzz' kena letak kat depan. lagipun code ini ditulis dlm keadaan aku tension banget sebab baru lepas kena marah dgn customer ... sad.gif

#8 mbek

    Leftenan Muda

  • Ahli
  • 785 posts
  • Gender:Male
  • Location:muwo
  • Interests:hehehehee
  • Kepakaran:Web Development (perl+php+mysql...)
  • Freelance:Ya

Posted 25 January 2007 - 04:55 PM

perl
CODE
foreach(1..100){
    if(($_ % 5 == 0) && ($_ % 3 == 0)){print "FizzBuzz \n";}
    elsif($_ % 3 == 0){print "Fizz \n";}
    elsif($_ % 5 == 0){print "Buzz \n";}
    else{print "$_\n";}
}


x reti nak buat perl 1 liner... heheheheilmu x cukup lg..

#9 mbek

    Leftenan Muda

  • Ahli
  • 785 posts
  • Gender:Male
  • Location:muwo
  • Interests:hehehehee
  • Kepakaran:Web Development (perl+php+mysql...)
  • Freelance:Ya

Posted 25 January 2007 - 05:16 PM

javascript
CODE
for(i=1;i<=100;i++){
    if((i % 5 == 0) && (i % 3 == 0)){document.write("FizzBuzz <br>");}
    else if(i % 3 == 0){document.write("Fizz <br>");}
    else if(i % 5 == 0){document.write("Buzz <br>");}
    else{document.write(i + "<br>");}
}


perl
CODE
foreach(1..100){(($_ % 3 == 0) && ($_ % 5 == 0)) ? print "FizzBuzz\n" : (($_ % 3 == 0) ? print "Fizz\n" : (($_ % 5 == 0) ? print "Buzz\n" : print $_ . "\n"));}


mcm ni bleh dikira 1 liner ker? hehehehehhe.... tongue.gif 1 line aper tu... hehehe

Edited by mbek, 25 January 2007 - 05:18 PM.


#10 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 25 January 2007 - 05:22 PM

Hahahaha... gembiranya rasa hati.. melihat code yang pelbagai..

mbek dah bagi code JavaScript, tapi aku ada satu JavaScript baru buat tadi. Tapi aku punya over-acting sket sebab pakai DOM. Ohohoho.. poyor betul..

CODE
<html>
    <head><title>FizzBuzz!</title></head>
    <body>
    </body>
</html>
<script type="text/javascript">
    for (i=1; i<101; i++)   {
        div = document.createElement("DIV");
        txt = '';
        
        if (!(i % 3))    txt += 'Fizz';
        if (!(i % 5))    txt += 'Buzz';
        
        if  ('' == txt)
            txt = i;
        else
            div.style.background = "yellow";
        
        div.appendChild(document.createTextNode(txt));
        document.body.appendChild(div);
    }
</script>


Hahaha. Best.. best.. aku ada beberapa komen menarik, tapi kita tunggu hingga hujung rancangan lah..


QUOTE(mbek @ Jan 25 2007, 05:16 PM) <{POST_SNAPBACK}>
mcm ni bleh dikira 1 liner ker? hehehehehhe.... tongue.gif
Haha.. one-liner la tu.. buang-buang linefeed jadi la.. yg penting nak tengok guna tertiary operator tu smile.gif
Tapi code one-liner pertama rasanya telah disubmit oleh kkmka90, cuma dia tak letak dlm 1 line, jadi setengah markah tongue.gif

Byk language tak cover lagi ni guys.. come on, bring it on!!! biggrin.gif

#11 k.anwar

    Staf Sarjan

  • Ahli
  • 189 posts
  • Gender:Male
  • Kepakaran:sket2 jboss,ejb3,java,rules
  • Freelance:Tidak

Posted 25 January 2007 - 05:35 PM

java

CODE
package my.anwar.jboss.drools.mbean;

public class PrintFizz {
    PrintFizz() {
    }

    public static void main(String[] args) {
        PrintFizz test = new PrintFizz();
        int a = 100;
        //org.jboss.util.StopWatch;
        long startTime = System.currentTimeMillis();
        
        while (a >= 1) {
            if (a % 3 == 0) {
                test.print("Fizz");
            }else if (a % 5 == 0) {
                test.print("Buzz");
            }
            if (a % 5 == 0 && a % 3 == 0) {
                test.print("FizzBuzz");
            } else {
                test.print("     " + a);
            }
            a--;
        }
        long time = System.currentTimeMillis() - startTime;
        test.print("time execution : " + time);
    }

    void print(String output) {
        System.out.println(output);
    }
}


ada banyak lagi cara aku rasa hehe..

#12 mbek

    Leftenan Muda

  • Ahli
  • 785 posts
  • Gender:Male
  • Location:muwo
  • Interests:hehehehee
  • Kepakaran:Web Development (perl+php+mysql...)
  • Freelance:Ya

Posted 25 January 2007 - 07:14 PM

QUOTE(1kHz @ Jan 25 2007, 05:22 PM) <{POST_SNAPBACK}>
Hahaha. Best.. best.. aku ada beberapa komen menarik, tapi kita tunggu hingga hujung rancangan lah..
Haha.. one-liner la tu.. buang-buang linefeed jadi la.. yg penting nak tengok guna tertiary operator tu smile.gif
Tapi code one-liner pertama rasanya telah disubmit oleh kkmka90, cuma dia tak letak dlm 1 line, jadi setengah markah tongue.gif


hahaha... aku buat tu pun stelah tgk code kmka90... cilok idea org... lagi poyo... hehehehhe

#13 ron

    Leftenan Muda

  • Ahli
  • 982 posts
  • Gender:Male
  • Location:KL
  • Interests:Information Security
  • Kepakaran:Software Development and Engineering
  • Freelance:Ya

Posted 25 January 2007 - 10:32 PM

C# lagi

CODE
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace FizzBuzz
{
    class Program
    {        
        static void Main(string[] args)
        {
            Stopwatch s = new Stopwatch();
            s.Start();
            
            for (int i = 1; i <= 16; i++)
            {                
                Console.WriteLine(Info(i));
            }

            s.Stop();
            TimeSpan ts = s.Elapsed;
            Console.WriteLine(String.Format("Masa diambil : {0:00}:{1:00}:{2:00}.{3:00}", +
                            ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10));

        }
                
        static string Info(int i)
        {
            string status = string.Empty;

            if ((i % 3) == 0)
                status = "Fizz";
            else if ((i % 5) == 0)
                status = "Buzz";
            else if (((i % 3) == 0) && ((i % 5) == 0))
                status = "FizzBuzz";
            else
                status = i.ToString();

            return status;

        }
    }
}

Edited by ron, 25 January 2007 - 10:41 PM.


#14 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 26 January 2007 - 12:20 AM

Ada tengok interview Scott Hanselman dan Jeffrey Snover (PowerShell Architect), teringin pulak nak tau mcm mana nak tulis code ni dlm PowerShell. Hence, this following monstrousity:
CODE
(1..100) | foreach($_){
    switch($_){
        {$_%15 -eq 0}{"FizzBuzz";break}
        {$_%3 -eq 0}{"Fizz";break}
        {$_%5 -eq 0}{"Buzz";break}
        default {$_}
    }
}

Jadi bapak monster bila buat one-liner:
CODE
(1..100) | foreach($_){ switch($_){ {$_%15 -eq 0}{"FizzBuzz";break} {$_%3 -eq 0}{"Fizz";break} {$_%5 -eq 0}{"Buzz";break} default{$_} } }

Hohoho.. come on.. lagi.. lagi laugh.gif

p.s: Yg menariknya, switch statement dia boleh compare to expression atau regex.. Mcm Ruby punya switch. Perl pun boleh buat camtu gak kot?

Edited by 1kHz, 26 January 2007 - 12:24 AM.


#15 ed_thix

    Sarjan Mejar

  • Ahli
  • 273 posts
  • Gender:Male
  • Location:Somewhere on the net..
  • Freelance:Tidak

Posted 26 January 2007 - 12:47 AM

Pinjam code 1khz ni dalam ruby (ntah betul tak, nak zzzz)

CODE
1.upto(100) do |i|
    div3 = (i % 3 == 0)
    div5 = (i % 5 == 0)
    
    p i if !div3 and !div5
    p 'Fizz' if div3
    p 'Buzz' if div5
end



biggrin.gif

Edited by ed_thix, 26 January 2007 - 12:48 AM.


#16 k4ml

    Leftenan Muda

  • Ahli Professional
  • 834 posts
  • Location:KB
  • Kepakaran:Linux, Freebsd, PHP, Drupal, PostgreSQL
  • Freelance:Ya

Posted 26 January 2007 - 07:13 AM

python lagi. guna map():-

CODE
def fizzbuzz(num):
if num % 3 == 0 and num % 5 == 0: return 'FizzBuzz'
elif num % 3 == 0: return 'Fizz'
elif num % 5 == 0: return 'Buzz'
else: return num

print map(fizzbuzz, range(1, 101))

dan list comprehensions:-

CODE
print [fizzbuzz(num) for num in range(1, 101)]

Edited by k4ml, 26 January 2007 - 07:14 AM.


#17 ron

    Leftenan Muda

  • Ahli
  • 982 posts
  • Gender:Male
  • Location:KL
  • Interests:Information Security
  • Kepakaran:Software Development and Engineering
  • Freelance:Ya

Posted 26 January 2007 - 08:57 AM

C#, code aku nampak panjang, ni aku pendekan lagi haha

CODE
using System;

namespace FizzBuzz
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 100; i++) { Console.WriteLine(Info(i)); }
        }

        static string Info(int i)
        {
            string status = string.Empty;

            if ((i % 3) == 0)
                status = "Fizz";
            else if ((i % 5) == 0)
                status = "Buzz";
            else if (((i % 3) == 0) && ((i % 5) == 0))
                status = "FizzBuzz";
            else
                status = i.ToString();

            return status;
        }
    }
}


#18 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 26 January 2007 - 09:20 AM

Siyut la k4ml, pakai map() pulak. Tak puas hati betul... dry.gif laugh.gif
Aku pun nak buat map pakai Ruby.
CODE
# map will return array, iterate to print
(1..100).map do |i|
    if    (i % 15).zero? then 'FizzBuzz'
    elsif (i %  3).zero? then 'Fizz'
    elsif (i %  5).zero? then 'Buzz'
    else i
    end
end.each { |j| puts j }

Satu lagi version yg lebih mudah dibaca
CODE
# collect and map do the same thing
arr = (1..100).collect do |i|
    if    (i % 15).zero? then 'FizzBuzz'
    elsif (i %  3).zero? then 'Fizz'
    elsif (i %  5).zero? then 'Buzz'
    else i
    end
end
puts arr

Edited by 1kHz, 26 January 2007 - 09:22 AM.


#19 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 26 January 2007 - 10:45 AM

Ceriakan dunia anda dengan flash blink.gif
CODE
i = 1; y_pos=20; x_pos=20;
this.onEnterFrame = function(){
i++;
if(i >= 100){ delete this.onEnterFrame; }
_root.createTextField("mytext" + i,i,x_pos,y_pos,50,25);
fuzzyWuzzy = ((i % 3 == 0) and (i % 5 == 0)) ? "FizzBuzz" :
((i % 3 == 0) ? "Fizz" :
((i % 5 == 0) ? "Buzz" : i));
_root['mytext'+i].text = fuzzyWuzzy
y_pos += 25
if ( y_pos >= Stage.height){ y_pos = 20; x_pos += 55;}
trace(i);
}

Result:


#20 ijam

    Korporal

  • Ahli
  • 57 posts
  • Location:BP - TRM - JHB - KIN
  • Kepakaran:minesweeper, toki toki boom
  • Freelance:Tidak

Posted 26 January 2007 - 10:52 AM

mbek, cilok anda punya Perl idea ye smile.gif

CODE
bash-2.03$ perl -e'print+((($_%3)||($_%5))?"":FizzBuzz)||(($_%3)?"":Fizz)||(($_%5)?"":Buzz)||$_,$/for 1..100'


Buang bahagian FizzBuzz dan kita combine Fizz dan Buzz dgn dot operator

bash-2.03$ perl -e'print+((($_%3)||($_%5))?"":FizzBuzz)||(($_%3)?"":Fizz)||(($_%5)?"":Buzz)||$_,$/for 1..100'

Jadi camni

CODE
bash-2.03$ perl -e'print+(($_%3)?"":Fizz).(($_%5)?"":Buzz)||$_,$/for 1..100'


#21 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 26 January 2007 - 12:22 PM

Perrrgh.. tergeliat otak nak baca one-liner Perl laugh.gif Boleh buat mcm tu eh?

Aku telah mengabaikan language yg aku guna sehari-harian. Jadi, inilah dia code VB.NET dari aku.. tapi... tak pakai loop, pakai recusion! Hambik kau...
CODE
Imports System

Public Module FizzBuzzGame
    
    Sub Main
        FizzBuzz(1, 100)
        Console.ReadLine()
    End Sub
    
    Sub FizzBuzz(ByVal start As Integer, ByVal [stop] As Integer)
        If start Mod 15 = 0 Then
            Console.WriteLine("FizzBuzz")
        ElseIf start Mod 3 = 0 Then
            Console.WriteLine("Fizz")
        ElseIf start Mod 5 = 0 Then
            Console.WriteLine("Buzz")
        Else
            Console.WriteLine(start.ToString())
        End If
        
        If start < [stop] Then FizzBuzz(start+1, [stop])    ' Recurse!
        
    End Sub

End Module


Bring it on, babeh... Buahaha.. having so much fun!

p.s: stop tu keyword dlm VB, jadi kena kurung dlm angle-bracket [stop]

Edited by 1kHz, 26 January 2007 - 12:25 PM.


#22 ron

    Leftenan Muda

  • Ahli
  • 982 posts
  • Gender:Male
  • Location:KL
  • Interests:Information Security
  • Kepakaran:Software Development and Engineering
  • Freelance:Ya

Posted 26 January 2007 - 12:37 PM

XAML & C#

CODE
<TextPanel xmlns="http://schemas.microsoft.com/2003/xaml"
           xmlns:def="Definition" def:Language="C#"
        HorizontalAlignment="Center"
        Background="LightCyan">
    <Button Click="btnExecute" FontSize="72">
        Show Me!
    </Button>
    <def:Code>
        <![CDATA[
            void btnExecute(object el, ClickEventArgs args)
            {              
                for (int i = 1; i <= 100; i++) { MessageBox.Show(Info(i)); }
            }
            
            private string Info(int i)
            {
                string status = string.Empty;

               if ((i % 3) == 0)
                  status = "Fizz";
              else if ((i % 5) == 0)
                  status = "Buzz";
              else if (((i % 3) == 0) && ((i % 5) == 0))
                  status = "FizzBuzz";
              else
                  status = i.ToString();

              return status;
            }
        ]]>
    </def:Code>
</TextPanel>


#23 Helmi 0mar

    Leftenan Muda

  • Ahli Professional
  • 553 posts
  • Gender:Male
  • Location:shah alam
  • Interests:tgk tv
  • Kepakaran:ym
  • Freelance:Tidak

Posted 29 January 2007 - 10:56 AM

QUOTE(ijam @ Jan 26 2007, 10:52 AM) <{POST_SNAPBACK}>
Jadi camni
CODE
bash-2.03$ perl -e'print+(($_%3)?"":Fizz).(($_%5)?"":Buzz)||$_,$/for 1..100'

waaaahh ohmy.gif
ini yg aku tunggu2.. perl 1-line.. kagum2 dgn perl.. aku rasa mcm nak kamceng dgn perl blk laa.. laugh.gif

#24 ijam

    Korporal

  • Ahli
  • 57 posts
  • Location:BP - TRM - JHB - KIN
  • Kepakaran:minesweeper, toki toki boom
  • Freelance:Tidak

Posted 29 January 2007 - 01:24 PM

Helmi 0mar, bile dah kamceng balik dengan Perl, bole la join Perl Golf Competition laugh.gif

#25 ed_thix

    Sarjan Mejar

  • Ahli
  • 273 posts
  • Gender:Male
  • Location:Somewhere on the net..
  • Freelance:Tidak

Posted 29 January 2007 - 01:52 PM

ruby in 1 line

CODE
1.upto(100)  { |i| d3 = (i % 3 == 0);d5 = (i % 5 == 0);db = (d3 && d5); p i if !d3 && !d5 && !db;  if db; p 'FizzBuzz'; else; p 'Fizz' if d5; p 'Buzz' if d3; end;  }


#26 amry

    Kapten

  • Core
  • 2,178 posts
  • Gender:Male
  • Location:Wangsa Maju
  • Kepakaran:Programming
  • Freelance:Tidak

Posted 29 January 2007 - 02:10 PM

Pada pendapat aku yang tak seberapa ini, apa kata cukup la dengan one liner yang sebenarnya tak one liner tu. Pada aku, kalau code tu jadi one liner just by removing the newlines padahal sebenarnya dia dah terdiri daripada beberapa statement (diasingkan dengan simbol semicolon dalam beberapa bahasa), tu hanya mengurangkan readability, not really worth the one line rule.

#27 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 29 January 2007 - 02:30 PM

Yes. Reduce the insanity please.

#28 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 29 January 2007 - 02:32 PM

Dah byk gak code ni, hohoho best. Mari submit lagi. Sementara menunggu korang fikir, ingin rasanya hati ini utk menghighlightkan beberapa point yg rasanya menarik:

Helmi (#2) yang mula2 notice `num % 3 AND num % 5` adalah setara dgn `num % (3*5)` (atau shortcutnya `num % 15`, the fact that 15 adalah gandaan sepunya terkecil bagi 3 dan 5). Jadi utk menguji kondisi "FizzBuzz", dpt elak dari buat 3 operasi (x MODULUS 3, AND, x MODULUS 5).

Aku terfikir2 boleh ke buat dlm SQL, this language that we love to hate would be unusually hard to bend in certain situations, but k4ml (#7) telah membuktikan ia boleh dilakukan dgn PostgreSQL. I wonder dlm DB lain boleh ke tidak? Oracle mcm boleh je, MSSQL entah boleh atau tak?

One-liners melalui penggunaan "ternary operator" `a ? b : c` telah didemonstrasikan olek kkmka90 (#4), mbek (#9), and most impresively by ijam (#20). Betul ke boleh mcm tu, aku takde Perl installed, so percaya je lah. Sure, it obfuscates the algo, buat mata juling, but heck, it's a nice way to make people know you are l33t. w00t! (p.s: Please dont do it in production code tongue.gif )

Persembahan penuh visual dari kkmka90 (#19) dan ron (#22) masing2 menggunakan Flash Action Script dan XAML. Walaupun nampak mcm cuba memancing undi utk trofi persembahan terbaik, namun sebenarnya kod mcm ni la antara yg nak kita tengok. Simple demonstration of some (almost) unfamiliar language.

Teringin nak tengok functional language, takde org kat sini tahu la kot? Lisp ke, Scheme ke, Haskell, Erlang, OCaml? Ada?

Kalau boleh think out of the box.. Let us see how far out we can go.

Language kegemaran anda masih belum tersenarai lagi? Mari, mari.. Submit code anda.

Edited by 1kHz, 29 January 2007 - 03:09 PM.


#29 nyem

    Kadet

  • Ahli Biasa
  • 49 posts
  • Freelance:Ya

Posted 29 January 2007 - 02:39 PM

QUOTE(amry @ Jan 29 2007, 02:10 PM) <{POST_SNAPBACK}>
Pada pendapat aku yang tak seberapa ini, apa kata cukup la dengan one liner yang sebenarnya tak one liner tu. Pada aku, kalau code tu jadi one liner just by removing the newlines padahal sebenarnya dia dah terdiri daripada beberapa statement (diasingkan dengan simbol semicolon dalam beberapa bahasa), tu hanya mengurangkan readability, not really worth the one line rule.


If it can do the same thing, why not? the purpose of this exercise is just to create a program, readability is not one of the criteria. Bak kat pujangga perl there is more than one way to do it. With one-liner you can execute it directly from the command line, and impress your future employer.

#30 efaisal

    Sarjan Mejar

  • Ahli
  • 258 posts

Posted 29 January 2007 - 03:01 PM

Just for the fun of it, using GNU Bash

CODE
for ((i=1; i < 101; i++)); do [[ $(($i % 15)) -eq 0 ]] && echo "FizzBuzz" && continue; [[ $(($i % 5)) -eq 0 ]] && echo "Buzz" && continue; [[ $(($i % 3)) -eq 0 ]] && echo "Fizz" && continue; echo $i; done


#31 k4ml

    Leftenan Muda

  • Ahli Professional
  • 834 posts
  • Location:KB
  • Kepakaran:Linux, Freebsd, PHP, Drupal, PostgreSQL
  • Freelance:Ya

Posted 29 January 2007 - 03:12 PM

QUOTE(1kHz @ Jan 29 2007, 02:32 PM) <{POST_SNAPBACK}>
Aku terfikir2 boleh ke buat dlm SQL, this language that we love to hate would be unusually hard to bend in certain situations, but k4ml (#7) telah membuktikan ia boleh dilakukan dgn PostgreSQL. I wonder dlm DB lain boleh ke tidak? Oracle mcm boleh je, MSSQL entah boleh atau tak?

CASE is ANSI SQL so should be doable in any dialect that comform to ANSI SQL.

#32 Helmi 0mar

    Leftenan Muda

  • Ahli Professional
  • 553 posts
  • Gender:Male
  • Location:shah alam
  • Interests:tgk tv
  • Kepakaran:ym
  • Freelance:Tidak

Posted 29 January 2007 - 03:13 PM

QUOTE(1kHz @ Jan 29 2007, 02:32 PM) <{POST_SNAPBACK}>
and most impresively by ijam (#20). Betul ke boleh mcm tu, aku takde Perl installed, so percaya je lah. Sure, it obfuscates the algo, buat mata juling, but heck, it's a nice way to make people know you are l33t. w00t! (p.s: Please dont do it in production code tongue.gif )

aku dah test code perl 1-liner tuu.. spt nyanyian siti: "percayalahhh..." , mmg result code tu success.. laugh.gif ..

#33 mnajem

    Kolonel

  • Ahli Professional
  • 4,570 posts
  • Gender:Male
  • Kepakaran:Linux
  • Freelance:Ya

Posted 29 January 2007 - 03:14 PM

QUOTE(efaisal @ Jan 29 2007, 03:01 PM) <{POST_SNAPBACK}>
Just for the fun of it, using GNU Bash

CODE
for ((i=1; i < 101; i++)); do [[ $(($i % 15)) -eq 0 ]] && echo "FizzBuzz" && continue; [[ $(($i % 5)) -eq 0 ]] && echo "Buzz" && continue; [[ $(($i % 3)) -eq 0 ]] && echo "Fizz" && continue; echo $i; done


boleh try guna GNU Awk pulak tak.

#34 amry

    Kapten

  • Core
  • 2,178 posts
  • Gender:Male
  • Location:Wangsa Maju
  • Kepakaran:Programming
  • Freelance:Tidak

Posted 29 January 2007 - 03:17 PM

QUOTE(nyem @ Jan 29 2007, 02:39 PM) <{POST_SNAPBACK}>
If it can do the same thing, why not? the purpose of this exercise is just to create a program, readability is not one of the criteria. Bak kat pujangga perl there is more than one way to do it. With one-liner you can execute it directly from the command line, and impress your future employer.

Tak, apa yang aku cuba maksudkan ialah aturcara yang asalnya banyak baris tapi jadi sebaris hanya dengan membuang newlines semata-mata. Kalau yang macam contoh Perl ko tu aku tengok pun kagum tapi aku tak tau Perl so no comment. Other than that, aku rasa aturcara kkmka90 yang pertama paling mendekati one liner sebab dia gunakan terniary operator.

#35 ed_thix

    Sarjan Mejar

  • Ahli
  • 273 posts
  • Gender:Male
  • Location:Somewhere on the net..
  • Freelance:Tidak

Posted 29 January 2007 - 03:17 PM

QUOTE
there is more than one way to do it.
O/T jap

TIMTOWDI - Tim Toady - I like this concept but choosing the right way always the problem heheheheh laugh.gif

QUOTE
Pada aku, kalau code tu jadi one liner just by removing the newlines padahal sebenarnya dia dah terdiri daripada beberapa statement (diasingkan dengan simbol semicolon dalam beberapa bahasa), tu hanya mengurangkan readability, not really worth the one line rule.


true, saja je tadi tu bosan2 laugh.gif don't take it seriously

#36 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 29 January 2007 - 03:34 PM

QUOTE(k4ml @ Jan 29 2007, 03:12 PM) <{POST_SNAPBACK}>
CASE is ANSI SQL so should be doable in any dialect that comform to ANSI SQL.
CASE memang boleh buat, tapi generate_series tu tak pasti ada equivalent dia dlm lain-lain SQL dialect.


QUOTE(Helmi 0mar @ Jan 29 2007, 03:13 PM) <{POST_SNAPBACK}>
aku dah test code perl 1-liner tuu.. spt nyanyian siti: "percayalahhh..." , mmg result code tu success.. laugh.gif ..
Ok, ok, sbb Siti dah cakap mcm tu, maka aku percaya smile.gif Rasanya boleh buat mcm tu (gunakan dot operator, utk concat strings?) sebab Perl treat empty string "" sebagai false? Betul ke? Sebab tu boleh OR kan dgn statement seterusnya.

Betul? Aku main tembak je ni.

#37 mbek

    Leftenan Muda

  • Ahli
  • 785 posts
  • Gender:Male
  • Location:muwo
  • Interests:hehehehee
  • Kepakaran:Web Development (perl+php+mysql...)
  • Freelance:Ya

Posted 29 January 2007 - 03:44 PM

uiks... jgn ler formal sgt... kita just nak tgk approach utk solve the problem dari different point of view... dgn tgk mcm2 jenis script dari pelbagai jenis language aku sendiri dpt mcm2 idea... walaupun script ni simple jer...

... come on coders.... giv us more... yeah.... vb, wakil dari assembly lang etc.. x de lg... some 1... share ur code here

#38 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 29 January 2007 - 03:59 PM

Lol, lek lek rakan rakan sekalian.

Ni aku dok godek godek, custom Java-based, open source processing language oleh Ben Fry. In other words, an abstraction layer on top of Java.

Ni la orang takde keje.. godek sana godek sini. sad.gif
Tapi guna cara sama ngan php dan actionscript yang aku submit biggrin.gif

Appletnya berada di http://mkhairul.com/fizzbuzz/index.html

CODE
float x, y;
float size = 40.0;
PFont font;
int fuzzy = 1;
String fizzWords;

void setup()
{
size(200, 200, P3D);
frameRate(24);
fizzWords = ((fuzzy % 3 == 0) && (fuzzy % 5 == 0)) ? "FizzBuzz" :
((fuzzy % 3 == 0) ? "Fizz" :
((fuzzy % 5 == 0) ? "Buzz" : Integer.toString(fuzzy)));
delay(0);
noStroke();
}

void draw()
{
background(102);

x = x + 5.0;

if(x > width)
{
x = -size;
fuzzy = fuzzy + 1;
fizzWords = ((fuzzy % 3 == 0) && (fuzzy % 5 == 0)) ? "FizzBuzz" :
((fuzzy % 3 == 0) ? "Fizz" :
((fuzzy % 5 == 0) ? "Buzz" : Integer.toString(fuzzy)));
}
translate(x, height/2-size/2, x);
font = loadFont("ArialMT-48.vlw");
textFont(font, height/2-size);
text(fizzWords, height/2-size, x);
}



#39 efaisal

    Sarjan Mejar

  • Ahli
  • 258 posts

Posted 29 January 2007 - 04:14 PM

QUOTE(mnajem @ Jan 29 2007, 03:14 PM) <{POST_SNAPBACK}>
boleh try guna GNU Awk pulak tak.

Boleh. Use the code below to run from the shell:

CODE
echo | gawk '{ for (i=1; i<101; i++) { if (i%15 == 0) { print "FizzBuzz"; continue; } if (i%5 == 0) { print "Buzz"; continue; } if (i%3 == 0) { print "Fizz"; continue; } print i; } }'


#40 nyem

    Kadet

  • Ahli Biasa
  • 49 posts
  • Freelance:Ya

Posted 29 January 2007 - 05:21 PM

QUOTE(k4ml @ Jan 29 2007, 03:12 PM) <{POST_SNAPBACK}>
CASE is ANSI SQL so should be doable in any dialect that comform to ANSI SQL.

generate_series is not ANSI SQL ... can't do it in mysql (unless you have a table with 1..100 numbers)

here's ijam's perl one-liner in javascript

CODE
for (var i=1;i<=100;i++)    {
    document.write(
        ((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)+'<br>'
    )
}



here's map function in javascript, to emulate k4ml's python

CODE
if (!Array.prototype.map) {
  Array.prototype.map = function(fun /*, thisp*/)  {
    var len = this.length;
    if (typeof fun != "function") throw new TypeError();
    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) res[i] = fun.call(thisp, this[i], i, this);
    }
    return res;
  };
}


function fizzbuzz(num)    {
    if (num % 3 == 0 && num % 5 == 0)
        return 'FizzBuzz'
  else if (num % 3 == 0)
      return 'Fizz'
  else if (num % 5 == 0)
      return 'Buzz'
  else
      return num
}

var arr=[];
for (var i=1;i<=100;i++)    {
    arr.push( i );
}

document.write( arr.map(fizzbuzz).join('<br>') );


#41 napi

    Kadet

  • Ahli Biasa
  • 5 posts
  • Gender:Male
  • Location:Cheras
  • Kepakaran:programming
  • Freelance:Ya

Posted 29 January 2007 - 05:23 PM

Assalamualaikum

try juga. gunakan Delphi 7

CODE

var
x:integer;
begin
for x:=1 to 100 do
if x mod ( 3 * 5 ) = 0 then
memo1.Lines.Add('FIZZ BUZZ')
else if x mod 3 = 0 then
memo1.Lines.Add('FIZZ')
else if x mod 5 = 0 then
memo1.Lines.Add('BUZZ')
else
memo1.Lines.Add(INTTOSTR(X));
end;


#42 k4ml

    Leftenan Muda

  • Ahli Professional
  • 834 posts
  • Location:KB
  • Kepakaran:Linux, Freebsd, PHP, Drupal, PostgreSQL
  • Freelance:Ya

Posted 29 January 2007 - 08:12 PM

QUOTE(nyem @ Jan 29 2007, 05:21 PM) <{POST_SNAPBACK}>
generate_series is not ANSI SQL ... can't do it in mysql (unless you have a table with 1..100 numbers)

yup, I missed that one. but generate_series() is just a built-in function come with postgresql 8 not an SQL construct, so you can always create your own.

cilok my ex-boss punya code (sorry boss, hehehe ):-

CODE
-- range() to emulate python's range(start, stop, step)
-- Note: "immutable" kind of makes this a pure function with no side effects
CREATE OR REPLACE FUNCTION range(int, int, int) RETURNS SETOF INT
LANGUAGE plpgsql IMMUTABLE AS '
DECLARE
i integer;
start alias for $1;
stop alias for $2;
step alias for $3;
BEGIN
i := start;

IF step = 0 THEN
EXIT;
END IF;

IF step > 0 THEN
LOOP
IF i >= stop THEN
EXIT;
END IF;
RETURN NEXT i;
i := i + step;
END LOOP;
ELSE
LOOP
IF i < stop THEN
EXIT;
END IF;
RETURN NEXT i;
i := i + step;
END LOOP;
END IF;
END;
';


-- Overloaded range() to emulate python's range(start, stop)
-- Written in the "sql" language because pgsql inlines SQL functions (faster).
CREATE OR REPLACE FUNCTION range(int, int) RETURNS SETOF INT
IMMUTABLE LANGUAGE SQL AS 'select * from range($1, $2, 1);';

-- Overloaded range() to emulate python's range(stop)
-- Written in the "sql" language because pgsql inlines SQL functions (faster).
CREATE OR REPLACE FUNCTION range(int) RETURNS SETOF INT
IMMUTABLE LANGUAGE SQL AS 'select * from range(0, $1, 1);';
sumber asal kat sini - http://szap.blogspot.com/

so maybe someone can try porting that code to mysql 5 stored procedure ... wink.gif

Edited by k4ml, 29 January 2007 - 08:13 PM.


#43 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 30 January 2007 - 04:01 PM

My pythonic solution for this exercise!

Python
CODE
for x in range(1, 101): print [[[str(x), 'Buzz'][x % 5 == 0], 'Fizz'][x % 3 == 0], 'FizzBuzz'][x % 5 == 0 and x % 3 == 0]

Edited by kkmka90, 30 January 2007 - 04:07 PM.


#44 kkmka90

    Leftenan Muda

  • Ahli
  • 569 posts
  • Gender:Male
  • Location:Damansara
  • Kepakaran:Webninja, Gomu gomu fruit
  • Freelance:Ya

Posted 30 January 2007 - 04:18 PM

Above isnt as pythonic as I'd hope.

Dok cari cari lagi jumpa Mark Pilgrim nye site.

So maybe ni lebih pythonic dari yang atas.

Python (more pythonic I hope!)
CODE
for x in range(1, 101): print (x % 3 == 0 and x % 5 == 0) and 'FizzBuzz' or ((x % 3 == 0) and 'Fizz' or ((x % 5 == 0) and 'Buzz' or str(x)))

Edited by kkmka90, 30 January 2007 - 04:18 PM.


#45 mkshukeri

    Kadet

  • Ahli Biasa
  • 19 posts
  • Gender:Male
  • Location:Uniten &lt;--> Penang
  • Interests:Blajar benda baru.. dan blajar benda yg aku ingat aku dh terer ... mUahahaha
  • Kepakaran:PHP, MySQL, Photoshop
  • Freelance:Tidak

Posted 18 March 2007 - 03:06 AM

---DELETED----

Edited by mkshukeri, 18 March 2007 - 03:15 AM.


#46 mkshukeri

    Kadet

  • Ahli Biasa
  • 19 posts
  • Gender:Male
  • Location:Uniten &lt;--> Penang
  • Interests:Blajar benda baru.. dan blajar benda yg aku ingat aku dh terer ... mUahahaha
  • Kepakaran:PHP, MySQL, Photoshop
  • Freelance:Tidak

Posted 18 March 2007 - 03:10 AM

Hohoho.. aku pon nak try jugak.. walaupon cam dh lewat jer....

soklan:

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


code dlm php

CODE
<?php

for($number=1;$number<=100;$number++){
    
    if($number%3 == 0){
        echo "Fizz";
    }
    if($number%5 == 0){
        echo "Buzz";
    }
    if($number%3 !=0 && $number%5 !=0){
        echo $i."<br>";
    }

}

?>


cam jadik jer kan... tongue.gif

Edited by mkshukeri, 18 March 2007 - 03:15 AM.


#47 otak

    Kadet

  • Ahli Biasa
  • 33 posts
  • Kepakaran:very basic cybercafe networking
  • Freelance:Ya

Posted 19 March 2007 - 03:08 AM

kalo aku wat guna mirc punya scripting bleh?
aku geti tu je..ehehe

#48 1kHz

    Kapten

  • Ahli Professional
  • 1,520 posts
  • Gender:Male
  • Location:Shah Alam
  • Kepakaran:.NET
  • Freelance:Tidak

Posted 19 March 2007 - 08:43 AM

QUOTE(otak @ Mar 19 2007, 03:08 AM) <{POST_SNAPBACK}>
kalo aku wat guna mirc punya scripting bleh?
aku geti tu je..ehehe
Pakai apa-apa language pun boleh bro...

#49 otak

    Kadet

  • Ahli Biasa
  • 33 posts
  • Kepakaran:very basic cybercafe networking
  • Freelance:Ya

Posted 19 March 2007 - 10:39 AM

QUOTE(1kHz @ Mar 19 2007, 08:43 AM) <{POST_SNAPBACK}>
Pakai apa-apa language pun boleh bro...

ok thanks..

alias otak_fizzbuz {
var %x = 1
while (%x <= 100) {
echo : $iif(!$regex($calc( %x /3),/[.]/i),Buzz,$iif(!$regex($calc( %x /5),/[.]/i),FizzBuzz,%x))
inc %x
}
}

Edited by otak, 19 March 2007 - 10:39 AM.


#50 otak

    Kadet

  • Ahli Biasa
  • 33 posts
  • Kepakaran:very basic cybercafe networking
  • Freelance:Ya

Posted 19 March 2007 - 03:27 PM

alias otak_fizzbuz {
var %x = 1
while (%x <= 100) {
echo : $iif(!$regex($calc( %x /3),/[.]/i),$iif(!$regex($calc( %x /5),/[.]/i),FizzBuzz,Fizz),$iif(!$regex($calc( %x /5),/[.]/i),Buzz,%x))
inc %x
}
}


ni versi betul.. silap baca soklan
tolong delete post yg kat atas pls laugh.gif





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users