Monday, February 21, 2011

FizzBuzz in AS3


I'm not sure why this didn't seem hard, but in 10 minutes I came up w/ this solution to fizzBuzz:

private function fizzBuzz():void{
  for (var i:int = 1; i <= 100; i++){
    var str:String = String(i) + " " ;
    if(i%3==0){
      str += "Fizz";
    }
    if(i%5==0){
      str += "Buzz";
    }
    trace(str);
  }
}

Was there an easier way to do this?  Could I refactor this down further in AS3?  I tried overcomplicating it for reuse, but then said, "why?"  I just need it to spit out Fizz, Buzz or FizzBuzz, and the value of i...so that's it for now...Go AS3, modulo, and procrastineering...

edit: After reviewing the code, I decided to expand it (yes, I wasted another 10 minutes on this), but now I can pass in to fizzBuzz any values so that I don't have to have my modulo hardcoded.  Here it is, eat your heart out :)


public function fizzBuzz(starter:int, ender:int, fizzer:int, buzzer:int):void{
for(var i:int = starter; i<=ender; i++){
var str:String = i + " ";
if(i % fizzer == 0){ str += "Fizz";}
if(i % buzzer == 0){ str += "Buzz";}
trace(str);
}
}

No comments:

Post a Comment