You probably seek How to generate a combination by its number. The algorithm consists of creating a sequence of C(a[i],i)
with i
iterating from the number of items in a combination downto 1, so that the sum of these C values is equal to your given number. Then those a[i]
get inverted by length-1 and produced as result. A code in Powershell that makes this run:
function getC {
# this returns Choose($big,$small)
param ([int32]$big,[int32]$small)
if ($big -lt $small) { return 0 }
$l=$big
$total=[int64]1
1..$small | % {
$total *= $l
$total /= $_
$l-=1
}
return $total
}
function getCombinationByNumber {
param([string[]]$array, [int32]$howMany, [int64[]]$numbers)
$total=(getc $array.length $howMany)-1
foreach($num in $numbers) {
$res=@()
$num=$total-$num # for lexicographic inversion, see link
foreach($current in $howMany..1) {
# compare "numbers" to C($inner,$current) as soon as getting less than "numbers" take "inner"
foreach ($inner in $array.length..($current-1)) {
$c=getc $inner $current
if ($c -le $num) {
$num-=$c
$res+=$inner
break;
}
}
}
# $numbers=0, $res contains inverted indexes
$res2=@()
$l=$array.length-1
$res | % { $res2+=$array[$l-$_] }
return $res2
} }
To launch, provide the function an array from which to get combinations, e.g. @(0,1,2,3,4,5,6,7,8,9)
, the number of items in a combination (3) and the number of combination, starting from zero. An example:
PS C:\Windows\system32> $b=@(0,1,2,3,4,5,6,7,8,9)
PS C:\Windows\system32> getCombinationByNumber $b 3 0
0
1
2
PS C:\Windows\system32> [String](getCombinationByNumber $b 3 0)
0 1 2
PS C:\Windows\system32> [String](getCombinationByNumber $b 3 102)
4 5 8