So lets say you are on a flight from DC to Seattle, and you forgot to download music to your phone. What a crappy hypothetical situation. Luckily, you have your trusty laptop, and a lack of creativity. So here we go, lets write FizzBuzz in powershell. The rules are simple. For all of the numbers between 1 and 100:

  • If the number is divisible by 3, print 'fizz'
  • If the number is divisible by 5, print 'buzz'
  • If the number is divisible by both 3 and 5, print 'fizzbuzz'
  • Otherwise print the number

Simple enough. The program practically writes itself. What recruiter wouldn't be impressed by fizzbuzz in powershell.

raw

for($i = 1; $i -le 100; $i++)
{
    if($i % 3 -eq 0)
    {
        Write-Host 'fizz' -NoNewline
    }
    if($i % 5 -eq 0)
    {
        Write-Host 'buzz' -NoNewline
    }
    elseif($i % 3 -ne 0)
    {
        Write-Host $i -NoNewline
    }
    Write-Host
}

Great that took about 30 seconds. So let's try something a little harder. Lets squish this into one confusing line. That's what scripting languages are for anyway right? You aren't cool until you can sqeeze a script down into a tiny confusing line of code.

raw

(1..100) | ForEach-Object { $out = $null; if($_ % 3 -eq 0){$out = 'fizz'} if($_ % 5 -eq 0){$out += 'buzz'} if(-not $out){$out = $_} $out}

Thats better. But I don't think its confusing enough yet. Lets use some of the preset aliases: '%' and 'oh'. '%' is short for "ForEach-Object" and 'oh' is short for "Out-Host". Where does that put us?

raw

(1..100)|%({if(-not($_%3)){$$='fizz'}if(-not($_%5)){$$+='buzz'}if(-not$$){$$=$_}$$|oh;$$=$__})

Now that's a mess. I am sure we can make this even shorter, but I am a little too sleepy now. Anyway, there is the elusive 1 liner powershell fizzbuzz solution.