php - How to know the possible sets of n numbers? -
i have set of numbers s = [1,2,3,4,5,6];
, want make possible pairs among them 1 thing know pair not repeat.
i have used :-
$pairs = array('1','2','3','4','5','6'); $count = count($pairs); $array = array(); for($i = 0;$i <= $count; $i++){ for($j = 1; $j < $count; $j++){ if($i < $j){ $array[$i][] = $pairs[$i].','.$pairs[$j]; } } }
i want thing :-
s = [1,2,3,4,5,6]; [1,2],[1,3],[1,4],[1,5],[1,6] [2,3],[2,4],[2,5],[2,6] [3,4],[3,5],[3,6] [4,5],[4,6] [5,6]
if have better suggestion please reply possible.
build double nested foreach
loop on array, build pairs , check if got them.
pseudocode:
pairs = [] foreach(entry in array) { foreach(entry2 in array) { pair = [entry, entry2] if(!alreadyexists(pair in pairs) { add(pair pairs) } } } havefun()
btw: won't hurt if try yourself, problem rather trivial.
Comments
Post a Comment