DBremen
8/27/2015 - 1:14 PM

Returns the cartesian product for an array of arrays

Returns the cartesian product for an array of arrays

#build the cartesian product for an array of arrays
function CartesianProduct($row, $currCol=0){
    if ($currCol -eq 0){
        $wordIndices = New-Object int[] $row.Length
    }
    $wordIndex = 0
    #walk through the items in the current column
    foreach($word in $row[$currCol]){
        #add the index to the indices for the current column
        $wordIndices[$currCol] =  $wordIndex
        $wordIndex++
        #if we reach the end of the row
        if ($currCol -eq ($row.Length - 1)) {
            $cartesianSet = @()
            $colIndex = 0
            foreach($column in $row){
                #add the items to the result set based on the collected indices
                $cartesianSet += $row[$colIndex][$wordIndices[$colIndex]]
                $colIndex++
            }
            $cartesianSet -join ','
        } 
        #do this for every column
        else {
            CartesianProduct $row ($currCol + 1)
        }
    }
}