PowerShell oneliner contest

The pipeline in PowerShell offers an avenue to solve many issues with oneliners.
My fellow Windows PowerShell MVP Carlo Mancini proposed a very interesting and high quality oneliner contest. Perfect, challenge accepted πŸ˜€
After reading the rules twice, I jumped into trying to figure out what’s the best approach to get the shortest solution for each puzzle. I usually focus on the approach before trying to shorten my solution because when you started digging in a hole, it’s hard to get out of it and come with a brand new approach to solve the puzzle.

  • Task 1: get the absolute value of the highest double floating point in an array

I noticed that the match operator with a regular expression allowed to filter out only double.

$n = -1,-2,-5,-8.9,'b',-9.11,-6,-3,-2,-9.1,-1,-1.4,'a'

# match with regular expression
$n -match '\d\.'

# vs. a more classic approach
$n | ? { $_ -is [double] }

There were only negative double numbers in the array. To get the shortest absolute value, I just multiplied by -1 instead of using the abs method of the [math] .Net class.

# .Net abs approach
[math]::abs(-1.4)

# vs. me cheating πŸ˜‰
-1.4*-1

After bringing all the pieces together, my shortest solution for task 1 is:

# task 1
($n-match'\.'|sort)[-1]*-1

posh-contest-task1

  • Task 2: display 12345 as a int32 without using digits

To solve this task, my idea/approach was to use hexadecimal and do some substractions

0xb-0xa -eq 1
0xc-0xa -eq 2
0xd-0xa -eq 3
0xe-0xa -eq 4
0xf-0xa -eq 5

…except that I can’t use the leading 0.
So, I wondered how do I get a hexadecimal without using the 0x notation.
Well the answer is:

# you can actually do 
[char]'f' - [char]'a'

My shortest solution for task 2 is:

# task 2
[int]-join('b','c','d','e','f'|%{([char]$_-[char]'a')})

posh-contest-task2

  • Task 3: Display PowerShell from ‘X ‘

When I saw this puzzle, I immediately thought, use only 1 occurrence of ‘X ‘, get rid of the whitespace behind X and use the ascii table to get P from X, o from X, w from X,…

My shortest solution was:

#task 3 split for readability
-join(
-8,23,31,13,26,-5,16,13,20,20|%{
[char]($_+[int][char]('X '-replace' ',''))
})

posh-contest-task3

PowerShell rocks 😎 and Bravo Carlo, I enjoyed this very nice contest πŸ™‚

Bonus: my favourite PS golfer Bartek also proposed his solutions: https://becomelotr.wordpress.com/2015/07/04/the-only-golf-i-play/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s