This function should REALLY come in handy for a lot of folks (heavy sarcasm). It calculates all size 2 subsets of an array whose values are unique, and in no particular order. So, passing it an array of [1,2,3] will return [[1,2],[1,3],[2,3]]. Passing it an array of [1,2,3,2,1,2,3] will return exactly the same thing. Go wild!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | function get_distinct_size_2_subsets($array) { $subsets = array(); // if the array only contains two or less element, just return it if (count($array) <= 2) return $array; for ($i=0; $i<count($array); $i++) { $curr_el1 = $array[$i]; for ($j=0; $j<count($array); $j++) { $curr_el2 = $array[$j]; if ($curr_el1 == $curr_el2) continue; // if an element of [$curr_el1, $curr_el2] and [$curr_el2, $curr_el1] doesn't exist, // add if to $subsets if (!in_array(array($curr_el1, $curr_el2), $subsets) && !in_array(array($curr_el2, $curr_el1), $subsets)) $subsets[] = array($curr_el1, $curr_el2); } } return $subsets; } |
Recent Comments