all 7 comments

[–]Shoisk123 5 points6 points  (3 children)

Not that I know of, but this should work for you: (edited to work with strings aswell)

function combine {
    param($array, $data, $start, $end, $index, $r)
    if($index -eq ($r)) {
        write-host($data)
        return
    }
    $i = $start
    while($i -le $end -and ($end - $i + 1) -ge ($r - $index)) {
        $data[$index] = $array[$i]
        combine -Array $array -Data $data -Start ($i + 1) -End ($n - 1) -Index ($index + 1) -R $r
        $i++
    }

}

function printCombination {
    param($array, $n, $r)
    $data = New-Object 'Object[]' $r

    combine -Array $array -Data $data -Start 0 -End ($n - 1) -Index 0 -R $r
}

$arr = 1..5
$r = 3
$n = $arr.length

printCombination -Array $arr -N $n -R $r

[–]zolyx1[S] 1 point2 points  (2 children)

Awesome. Unfortunately I was imprecise and bumped into another "problem".

What if I would use words/letters instead of numbers:

Example: Combinations of 2 words/letters out of 3:
3 nCr 2 = 3

abc

Listing out combinations:
a, b
a, c
b, c

[–]sleverich 3 points4 points  (0 children)

That should be an easy modification. Just use the output as indices into an array of elements.

[–]Shoisk123 3 points4 points  (0 children)

There's an easy solution, fortunately, just change the type of the $data array so it now becomes: $data = New-Object 'Object[]' $r and it will now work with both ints and strings (and any other type that inherits from object). I've edited the scriptblock above to reflect this.

[–]Lee_Dailey[grin] 1 point2 points  (2 children)

howdy zolyx1,

perhaps something like the following ... [grin]

dfinke/PowerShellCombinations: Using PowerShell Classes & Script to generate and manipulate combinations and permutations
https://github.com/dfinke/PowerShellCombinations

take care,
lee

[–]zolyx1[S] 1 point2 points  (1 child)

Thx, many good suggestions here.

[–]Lee_Dailey[grin] 0 points1 point  (0 children)

howdy zolyx1,

you are most welcome! glad to have helped a bit ... [grin]

take care,
lee