Finding all non-conflicting combinations of values from multiple lists of values

前端 未结 9 1046
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 05:34

I have the following array which contains arrays of values:

$array = array(
    array(\'1\', \'2\'),
    array(\'a\', \'b\', \'c\'),
    array(\'x\', \'y\'),         


        
9条回答
  •  一个人的身影
    2021-01-01 06:12

    Your problem is similar to that of finding a determinant of a matrix. The best way imho would be to fill smaller arrays with some symbol, say '0', so they all have equal number of values, in your example

    $array = array(
        array('1', '2', '0'),
        array('a', 'b', 'c'),
        array('x', 'y', '0'),
    );
    

    then loop through each of the first array values and for each increment the index of array by 1 and check the next array and the next column (on the first loop it will be '1' and index will be 0 incremented - 1, then get $array1 - 'b' and so on) if you reach '0', break, if you reach right border, reset first index to 0. Then do the same with decrementing and you'll have all the combinations. It is probably unclear, check the image I linked to

提交回复
热议问题