Friday, March 02, 2007

Powershell FizzBuzz One-liner

I know, I know, the FizzBuzz problem isn't about the implementation. However, I've seen implementations in C#, Java, Python, Perl, Ruby, yada, yada, yada. Well, I haven't seen one in Powershell, so I'm posting it here. Not for implementation's sake, because I'm sure that there is a better way to implement it. I'm putting it here for the sake of fairness.

1..100 ForEach-Object { $str = ""; if($_ % 3 -eq 0) { $str += "Fizz" }; if($_ % 5 -eq 0) { $str += "Buzz" }; if(($_ % 3 -ne 0) -and ($_ % 5 -ne 0)) { $str += $_ }; Write-Output $str }

3/8/2008 - Thanks to Scott for pointing out a typo in the script. It's fixed now.