Back to Basics: Exhaustive Enumeration in Powershell

I'm often overheard at work and customer engagements spreading the gospel about Powershell, encouraging everyone from the Junior SA to the most senior "engineer" to take advantage of this powerful language. Anyone can pick Powershell up and become quite productive in no time. One of the things I noticed however was a lack of fundamentals in the newly initiated. So I figured why not do my part and provide a few posts I'm calling "Back To Basics". These are foundational to any langauge, not just Powershell, so pick your poison. Feel free to post your samples in the comments.
Now lets get started with our first lesson, Exhaustive Enumeration.
So what is it? Put simply, exhaustive enumeration is trying all "possible" values until you find the solution.
I always find a problem useful for learning so lets use something simple we can all understand. Finding the square root of a perfect square.
So whats a square and a square root?
A square is a number multiplied by itself. So 3 x 3 = 9

Ok enough of that, how about some code?
PS C:\> [math]::sqrt(9) 3
No, no, no. Thats not it. The point of this code is to learn. We all know there are better ways to do things, but remember we are forcing a point here, so the code is representing that. Alright back to the matter at hand:
# Find the square root of a perfect square $x = Read-Host "Please enter a positive integer" $ans = 0 if ($x -as [int] -and $x -ge 0) { while ($ans * $ans -lt $x) { $ans = $ans + 1 Write-Verbose "Trying [$ans]" } if ($ans*$ans -ne $x) { Write-Host "$x is not a perfect square!" } else { Write-Host $ans } } else { Write-Host "$x is a negative number or a non-integer." }
Now lets see it in action:
PS H:\Development\Powershell> $VerbosePreference = "Continue" PS H:\Development\Powershell> .\ExhaustiveEnumeration.ps1 Please enter a positive integer: 9 VERBOSE: Trying [1] VERBOSE: Trying [2] VERBOSE: Trying [3] 3
So most of you are thinking man that must be slow! So lets take a larger number, say 1515361 and see how slow it is:
PS H:\Development\Powershell> Measure-Command {.\ExhaustiveEnumeration.ps1} 1231 Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 131 Ticks : 1310124 TotalDays : 1.51634722222222E-06 TotalHours : 3.63923333333333E-05 TotalMinutes : 0.00218354 TotalSeconds : 0.1310124 TotalMilliseconds : 131.0124
131 milliseconds, not bad. See computers are pretty good at this type of thing! Yes there are much more efficient ways to solve this, but you'll have to wait for a future post.






Reader Comments