## Combinatorics with PowerShell

Basic knowledge of combinatorics is essential for all software test engineers. A mathematical combination is a subset of a collection of items where order doesn’t matter. A mathematical permutation is a rearrangement of a collection of items. It is very useful to be able to programmatically manipulate combinations and permutations. Today I was pretty much blocked waiting for some hardware to arrive from Dell, and waiting for some phone messages to be returned, so I decided  to poke around combinatorics with PowerShell. The screenshot beloiw shows that I succeeded in getting a crude set of combination functions working. Because PowerShell is a scripting language it doesn’t support classes or structures, so I had to use global variables for n (the total number of items in the collection), k (the subset size), and values (an array to hold a combination element). Here is the main() function I used:

# demo.ps1
# string combinations with PowerShell
function main
{
write-host "`nbegin combinations with PowerShell demo`n"
\$data = ("ant","bat","cow","dog","elk","fox","gnu")
write-host "Initial data is: \$data `n"
makeCombination 7 3 \$data
for (\$i = 0; \$i -le 34; \$i++) {
if (\$i -lt 10 ) { write-host " " -nonewline }
write-host "[\$i] " -nonewline
displayCombination
incrementCombination
}

write-host "`nend combinations with PowerShell demo`n"
}

And here is the rather messy makeCombination() method:

function makeCombination(\$n,\$k,[string[]]\$d)
{
\$script:nVal = 0
\$script:kVal = 0
\$script:values = @()
\$script:all = @() # save all original strings
\$script:id  = @{} # hash table of original string ids
if (\$d.length -ne \$n) {
throw "Incorrect data array size: array size must equal n"
}
else {
\$script:nVal = \$n
\$script:kVal = \$k
\$script:values = new-object string[] \$k
for (\$i = 0; \$i -lt \$k; \$i++) {
\$script:values[\$i] = \$d[\$i]
}
# save all strings
\$script:all = new-object string[] \$n
for (\$i = 0; \$i -lt \$d.length; \$i++) {
\$script:all[\$i] = \$d[\$i]
}
# the ‘id’ of each string
for (\$i = 0; \$i -lt \$d.length; \$i++) {
\$script:id[\$d[\$i]] += \$i
}
} # else
} # makeCombination()

Anyway, it was a good exercise that taught me a few things about PowerShell syntax, and supported my notion that PowerShell makes an excellent base-language for lightweight software test automation.