Tuesday, August 21, 2007

FizzBuzz

As an assignment, I just finished the FizzBuzz in Java on Eclipse. It took me 35min to do so. Since learning java for not so long time and not writing codes in java for month, I have totally forget even the basic syntax structure such as where the program begins and how to output a word. It took me most of the time to getting the memory back by searching in java's doc, but get nothing. At last, I found the answers in the "helloworld" tutorials... After that, I just spend several minutes to finish the program.
Fundamental is of most importance because you can nothing without it. Just like the beginning of my programming, I have all the idea even the codes in my brain in C++, but I don't know how to write the correct code in java. Maybe the basic elements of java & C++ are almost the same, but just almost, to program right, we need the exactly right one. Though much of basic codes can be generate by the platform automatic, it did not provide me one. Therefore, be familiar with the programming language is all the time important.

Following is the codes of my FizzBuzz:

public class FizzBuzz {
public static void main(String args[])
{
for (int i=1;i<=100;++i)
{
if (i%3==0)
{ System.out.print("Fizz"); }
if(i%5==0)
{ System.out.print("Buzz"); }
if(i%3!=0 && i%5!=0)
{ System.out.print(i); }
System.out.println();
}
}//end of main()
}

I have just read all others blog associated with FizzBuzz. I found that they all (i%15) to find out the case when we need a "FizzBuzz". But in my codes, there is not an (i%15) because the "FizzBuzz" is composed by "Fizz" and "Buzz". "Fizz" comes from (i%3) and "Buzz" comes from (i%5), so no (i%15) is needed. Meanwhile, as both (i%3) and (i%5) will be executed in any case, I cannot simply use a else to cover the remaining cases. So there comes to be an (i%3!=0 && i%5!=0) . In this FizzBuzz case, my implementation needs 4 compare statment while the other just take 3. But when the factor increase, such as FizzBuzzDozz(3,5,7), my way increase 2 compare statment every new factor while the other increase by P(n+1,2)-P(n,2)=n. That will be huge when factor become more. And, some of the item will easily be forgotten.
However, it looks like the algorithmic thing rather than the software engineering one... Anyway, just left it here :)

No comments: