As an assignment for ICS 413, I timed myself in writing a simple FizzBuzz Program. I suspect this will become a recurring assignment that will be used as a metric of our progress in the course.
Requirements:
A method that returns a FizzBuzz String.
A FizzBuzz String can be defined as: a String where the numbers 1 through j are printed out according to the following conditions:
- One number per line.
- The multiples of 3 replaced by "Fizz".
- The multiples of 5 replaced by "Buzz".
- The multiples of both 3 and 5 replaced by "FizzBuzz".
3m 13s
Code:
public class FizzBuzz {
public static void main(String[] Args){
System.out.print(fizzBuzz(100));
}
public static String fizzBuzz(int j){
String s="";
Boolean b=false;
for(int i =1;i<=j;i++){
b=false;
if(i%3==0){
s+="Fizz";
b=true;
}
if(i%5==0){
s+="Buzz";
b=true;
}
if(!b){
s+=i;
}
s+="\n";
}
return s;
}
Approach:
My approach to the problem was to iterate through the numbers 1 to j, checking for multiples of 3 or 5, and appending the correct output. My implementation removes the need to check for multiples of both 3 and 5 as both conditions will trigger (appending "Buzz" to "Fizz") before the new line character is appended.
Conclusions:
This exercise illustrates how even a simple FizzBuzz program can speak volumes about a programmer. One's attention to detail, eye for optimization, and thought process can be dissected out of a few dozen lines of code.
I believe I spent about a third of my time simply planning out how to solve the problem, and trying to minimize the number of checks in the program. Despite this, I suspect there is still room for optimization in finding a way to determine whether or not the number should be printed. I implemented a Boolean variable to keep track of whether or not to print the number, but this added another check statement. I will investigate this further in the next FizzBuzz post.
No comments:
Post a Comment