php - Generating all combinations of possible clicked checkboxes to add the values -
i have generate possible combinations of 4 checkboxes order not matter. reason order not matter because add values connected checkboxes.
the array of categories is: ['kw1','kw2','kw3','kw4']
this means kw1+kw2 = kw2+kw1
. must seen 1 combination.
i've gotten pretty far, failing wrap head around it.
first of all, user can click between 1 , 4 checkboxes, there no fixed amount of checked checkboxes required. can translated loop:
for($i=1;$i<=4;$i++){ }
when 1 checkbox can clicked, there 4 possible options. when 4 checkboxes checked, 1 option available. when 1st checkbox checked, there 3 options left. when 2nd checkbox checked, 2 options remain available. drill.
i translated to:
for($i=1;$i<=4;$i++){ $j = 5 - $i; $reverse_j = 0; $categories = array('kw1','kw2','kw3','kw4'); for($j;$j>0;$j--){ $reverse_j++; $counter = 0; foreach($categories $category){ $counter++; $tmp = $categories; if($counter <= $i){ $result[$i][$reverse_j][] = $tmp[0]; unset($tmp[0]); $tmp = array_values($tmp); } } unset($categories[0]); $categories = array_values($categories); } }
the above 1 of many failed attempts trying generate combinations. i've written out combinations, because not hard, want create code it.
the possible combinations should be:
1 click = (1), (2), (3), (4) 2 clicks = (1-2), (1-3), (1-4), (2-3) ,(2-4), (3-4) 3 clicks = (1-2-3), (1-2-4), (1-3-4), (2-3-4) 4 clicks = (1-2-3-4)
what missing? thinking go wrong?
thanks comment of @dr_debug, found right term looking for: 'powerset'.
with term found following post: power set elements of length
this gave me following functions:
function subsets_n($arr, $k) { if (count($arr) < $k) return array(); if (count($arr) == $k) return array(0 => $arr); $x = array_pop($arr); if (is_null($x)) return array(); return array_merge(subsets_n($arr, $k), merge_into_each($x, subsets_n($arr, $k-1)) ); } function merge_into_each($x, $arr) { foreach ($arr &$a) array_push($a, $x); return $arr; }
with these functions, can generate array possible combinations!
Comments
Post a Comment