PHP: How to get all possible combinations of 1D array?
I believe your professor will be happier with this solution:
<?php
$array = array('Alpha', 'Beta', 'Gamma', 'Sigma');
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0, $iMax = sizeof($arr); $i < $iMax; $i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the i'th element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
?>
This solves it:
Array
(
[0] => Alpha
[1] => Alpha Beta
[2] => Alpha Beta Gamma
[3] => Alpha Beta Gamma Sigma
[4] => Alpha Beta Sigma
[5] => Alpha Beta Sigma Gamma
[6] => Alpha Gamma
[7] => Alpha Gamma Beta
[8] => Alpha Gamma Beta Sigma
[9] => Alpha Gamma Sigma
[10] => Alpha Gamma Sigma Beta
[11] => Alpha Sigma
[12] => Alpha Sigma Beta
[13] => Alpha Sigma Beta Gamma
[14] => Alpha Sigma Gamma
[15] => Alpha Sigma Gamma Beta
[16] => Beta
[17] => Beta Alpha
[18] => Beta Alpha Gamma
[19] => Beta Alpha Gamma Sigma
[20] => Beta Alpha Sigma
[21] => Beta Alpha Sigma Gamma
[22] => Beta Gamma
[23] => Beta Gamma Alpha
[24] => Beta Gamma Alpha Sigma
[25] => Beta Gamma Sigma
[26] => Beta Gamma Sigma Alpha
[27] => Beta Sigma
[28] => Beta Sigma Alpha
[29] => Beta Sigma Alpha Gamma
[30] => Beta Sigma Gamma
[31] => Beta Sigma Gamma Alpha
[32] => Gamma
[33] => Gamma Alpha
[34] => Gamma Alpha Beta
[35] => Gamma Alpha Beta Sigma
[36] => Gamma Alpha Sigma
[37] => Gamma Alpha Sigma Beta
[38] => Gamma Beta
[39] => Gamma Beta Alpha
[40] => Gamma Beta Alpha Sigma
[41] => Gamma Beta Sigma
[42] => Gamma Beta Sigma Alpha
[43] => Gamma Sigma
[44] => Gamma Sigma Alpha
[45] => Gamma Sigma Alpha Beta
[46] => Gamma Sigma Beta
[47] => Gamma Sigma Beta Alpha
[48] => Sigma
[49] => Sigma Alpha
[50] => Sigma Alpha Beta
[51] => Sigma Alpha Beta Gamma
[52] => Sigma Alpha Gamma
[53] => Sigma Alpha Gamma Beta
[54] => Sigma Beta
[55] => Sigma Beta Alpha
[56] => Sigma Beta Alpha Gamma
[57] => Sigma Beta Gamma
[58] => Sigma Beta Gamma Alpha
[59] => Sigma Gamma
[60] => Sigma Gamma Alpha
[61] => Sigma Gamma Alpha Beta
[62] => Sigma Gamma Beta
[63] => Sigma Gamma Beta Alpha
)
PHP Find All (somewhat) Unique Combinations of an Array
If you don't mind using a couple of global variables, you could do this in PHP (translated from a version in JavaScript):
<?PHP
$result = array();
$combination = array();
function combinations(array $myArray, $choose) {
global $result, $combination;
$n = count($myArray);
function inner ($start, $choose_, $arr, $n) {
global $result, $combination;
if ($choose_ == 0) array_push($result,$combination);
else for ($i = $start; $i <= $n - $choose_; ++$i) {
array_push($combination, $arr[$i]);
inner($i + 1, $choose_ - 1, $arr, $n);
array_pop($combination);
}
}
inner(0, $choose, $myArray, $n);
return $result;
}
print_r(combinations(array(20,20,22,24), 3));
?>
OUTPUT:
Array ( [0] => Array ( [0] => 20
[1] => 20
[2] => 22 )
[1] => Array ( [0] => 20
[1] => 20
[2] => 24 )
[2] => Array ( [0] => 20
[1] => 22
[2] => 24 )
[3] => Array ( [0] => 20
[1] => 22
[2] => 24 ) )
Get all combinations using patterns and store to one array
Not really a complete answer, but might help. Will revisit in future:
It is actually useful to convert your print_r to JSON or an array. This is helpful for that. php-print_r-to-json-online
That at least makes it easy to convert that to an array with the json from above. I made some modifications. You would have to put your json / array into $array.
$array = json_decode($json, true);
$result = array_map( function($a) { return $a['roomInfo']['requestedRoomIndex']; }, $array);
print_r($result);
$uniquevalues = array_unique($result);
$configarray = [];
foreach ($uniquevalues as $key => $value) {
$configarray[$value] = array_filter($result, function($v, $k) use ($value) { if ($v == $value) return $v ;}, ARRAY_FILTER_USE_BOTH);
}
function get_combinations($arrays) {
$result = array(array());
foreach ($arrays as $property => $property_values) {
$tmp = array();
foreach ($result as $result_item) {
foreach ($property_values as $property_key => $property_value) {
$tmp[] = $result_item + array(current($property_values) => $property_key);
}
}
$result = $tmp;
}
return $result;
}
$results = [];
foreach(get_combinations($configarray) as $combo) {
// $results[] = implode($combo, "-");
$results[] = $combo;
}
print_r($results);
Did a little more looking. Still not absolutely certain what you are looking for, but I made some changes.
The results of that are:
Array
(
[0] => 3
[1] => 3
[2] => 2
[3] => 2
[4] => 1
)
Array
(
[0] => Array
(
[3] => 0
[2] => 2
[1] => 4
)
[1] => Array
(
[3] => 0
[2] => 3
[1] => 4
)
[2] => Array
(
[3] => 1
[2] => 2
[1] => 4
)
[3] => Array
(
[3] => 1
[2] => 3
[1] => 4
)
)
The results array has 4 arrays, having the combinations that I think you are looking for ??
How can I get all possible combinations of element in set? (power set)
You can use the following recursion function:
function powerSet($arr) {
if (!$arr) return array([]);
$firstElement = array_shift($arr);
$recursionCombination = powerSet($arr);
$currentResult = [];
foreach($recursionCombination as $comb) {
$currentResult[] = array_merge($comb, [$firstElement]);
}
return array_merge($currentResult, $recursionCombination );
}
Now print_r(powerSet([1,2,3]));
will give you all those option as arrays.
Edited with adding option of empty array as powerSet
Getting All combinations from an array PHP
try this:
$courses=array('English','Math','Algebra','History','Computer(lec)');
$sizes = array('1','3','3','3','2');
//maximum 6 hours
$limit=9;
//minimum number of 3 courses
$minimum=3;
$possible= array();
function get_comb($previous, $depth){
global $courses;
$count=count($courses);
global $possible;
global $sizes;
global $limit;
global $minimum;
if ($depth>$count){
$size_of_course=0;
foreach($previous as $nr=>$course){
if($course !== 0){
$size_of_course+=$sizes[$nr];
}
else{
//remove zeros
unset($previous[$nr]);
}
}
if ($size_of_course<=$limit&&count($previous)>=$minimum){
$possible[]=$previous;
}
return;
}
//either you have this course...
get_comb(array_merge($previous,array($courses[$depth-1])),$depth+1);
//or you dont..
get_comb(array_merge($previous,array(0)),$depth+1);
}
get_comb(array(),1);
//output
echo '<pre>';
var_dump($possible);
in the variable previous the courses add up while the function does recursion.
Explanation:
first, i calculate all the possible combinations.
To do this, I thought of the courses as slots:
whether you take the course or not, possibilities:
course a course b
yes yes
yes no
no yes
no no
this is done with this part of the function. It is a recursive function, so it calls itself within the function:
function get_comb($previous, $depth){
//either you have this course...
get_comb(array_merge($previous,array($courses[$depth-1])),$depth+1);
//or you dont..
get_comb(array_merge($previous,array(0)),$depth+1);
}
get_comb(array(),1);
assuming this:
$courses=array('course a','course b');
the recursive function calls would look like this (0 means, you dont take that course):
http://img43.imageshack.us/img43/5688/flowdiagram.png
after that, if they fit the requirements I save the possibility in $possible:
because depth=3 and count=2, $depth>$count so this part of the code comes into play:
if ($depth>$count){
$size_of_course=0;
foreach($previous as $nr=>$course){
if($course !== 0){
//the index of $previous is the same as in $courses and $sizes, so
//$previous[1],$courses[1],$sizes[1] is logicaly referring to the same course
//add up all sizes of the courses that are used in this possibility
$size_of_course+=$sizes[$nr];
}
else{
//remove zeros
unset($previous[$nr]);
}
}
//the size of the course has to be lower or same as the size limit
//now without the zeros, count($previous) gives you the amount of courses taken in this possibility
if ($size_of_course<=$limit&&count($previous)>=$minimum){
//if it fits, save this possibility in the $possible array
$possible[]=$previous;
}
return;
}
hope i could help you.
---------------------------------------------edit--------------------------------------
to archieve this: 'if there is computer(lec) it would only accept it as a possible combination if computer(lab) is also present':
replace $possible[]=$previous;
with:
//further conditions are placed here
//IMPORTANT: the name of the courses down here (in_array('Computer(lec)') have to be EXACTLY the same as in the array $courses.
//e.g. if in $courses array the name is 'computer(lec)' and down here it's 'Computer(lec)' (uppercase) or 'computer (lec)' (space) it DOES NOT WORK!
//if Computer(lec) is present...
if(in_array('Computer(lec)',$previous)){
//Computer(lab) has to be present too
if(in_array('Computer(lab)',$previous)){
$possible[]=$previous;
}
else {
//if its not present dont save
//do nothing
}
}
else{
//if computer(lec) is not present, no problem, just save
$possible[]=$previous;
}
so the finished code would be
$courses=array('English','Math','Computer(lec)','Computer(lab)');
$sizes = array('1','1','2','2');
//maximum 6 hours
$limit=9;
//minimum 3 courses
$minimum=0;
$possible= array();
function get_comb($previous, $depth){
global $courses;
$count=count($courses);
global $possible;
global $sizes;
global $limit;
global $minimum;
//the end of the $courses array is reached
if ($depth>$count){
$size_of_course=0;
foreach($previous as $nr=>$course){
if($course !== 0){
//the index of $previous is the same as in $courses and $sizes, so
//$previous[1],$courses[1],$sizes[1] is logicaly referring to the same course
//add up all sizes of the courses that are used in this possibility
$size_of_course+=$sizes[$nr];
}
else{
//remove zeros
unset($previous[$nr]);
}
}
//the size of the course has to be lower or same as the size limit
//now without the zeros, count($previous) gives you the amount of courses taken in this possibility
if ($size_of_course<=$limit&&count($previous)>=$minimum){
//further conditions are placed here
//IMPORTANT: the name of the courses down here (in_array('Computer(lec)') have to be EXACTLY the same as in the array $courses.
//e.g. if in $courses array the name is 'computer(lec)' and down here it's 'Computer(lec)' (uppercase) or 'computer (lec)' (space) it DOES NOT WORK!
//if Computer(lec) is present...
if(in_array('Computer(lec)',$previous)){
//Computer(lab) has to be present too
if(in_array('Computer(lab)',$previous)){
$possible[]=$previous;
}
else {
//if its not present dont save
//do nothing
}
}
else{
//if computer(lec) is not present, no problem, just save
$possible[]=$previous;
}
}
return;
}
//either you have this course...
get_comb(array_merge($previous,array($courses[$depth-1])),$depth+1);
//or you dont..
get_comb(array_merge($previous,array(0)),$depth+1);
}
get_comb(array(),1);
//output
echo '<pre>';
var_dump($possible);
How to generate in PHP all combinations of items in multiple arrays
Here is recursive solution:
function combinations($arrays, $i = 0) {
if (!isset($arrays[$i])) {
return array();
}
if ($i == count($arrays) - 1) {
return $arrays[$i];
}
// get combinations from subsequent arrays
$tmp = combinations($arrays, $i + 1);
$result = array();
// concat each array from tmp with each element from $arrays[$i]
foreach ($arrays[$i] as $v) {
foreach ($tmp as $t) {
$result[] = is_array($t) ?
array_merge(array($v), $t) :
array($v, $t);
}
}
return $result;
}
print_r(
combinations(
array(
array('A1','A2','A3'),
array('B1','B2','B3'),
array('C1','C2')
)
)
);
PHP Get all combinations between 2 arrays
TRY:
$array1 = array('A', 'B');
$array2 = array('1', '2', '3');
$num = count($array2);
$comb = array();
//The total number of possible combinations
$total = pow(2, $num);
//Loop through each possible combination
for ($i = 0; $i < $total; $i++)
{
$flag = '';
//For each combination check if each bit is set
for ($j = 0; $j < $num; $j++)
{
//Is bit $j set in $i?
if (pow(2, $j) & $i)
$flag = $flag.''.$array2[$j];
}
if(!empty($flag))
$comb[] = $flag;
}
// Now $comb has all the possible combinations of $array2
// Just loop it through the other array and concat
$result = array();
foreach($array1 as $val)
{
foreach($comb as $co)
$result[] = $val."".$co;
}
print_r($result);
RESULT:
Array
(
[0] => A1
[1] => A2
[2] => A12
[3] => A3
[4] => A13
[5] => A23
[6] => A123
[7] => B1
[8] => B2
[9] => B12
[10] => B3
[11] => B13
[12] => B23
[13] => B123
)
DEMO:
http://3v4l.org/LdNlI
Get all possible combinations of a PHP Array split in two
Just googled and found these results from stackoverflow.com
Get all combinations of a PHP array
algorithm that will take numbers or words and find all possible combinations
PHP: How to get all possible combinations of 1D array?
Related Topics
Why Does MySQLi Num_Rows Always Return 0
Find a Matching or Closest Value in an Array
How to Find the Mime Type of a File With PHP
Why Is Facebook PHP Sdk Getuser Always Returning 0
Issue Reading Http Request Body from a Json Post in PHP
Replace the Variable Price Range by the Chosen Variation Price in Woocommerce 3
MySQLi: Can It Prepare Multiple Queries in One Statement
Tracking the Script Execution Time in PHP
What Are the Differences in Die() and Exit() in PHP
Explode PHP String by New Line
Diagnosing Memory Leaks - Allowed Memory Size of # Bytes Exhausted
Are Arrays in PHP Copied as Value or as Reference to New Variables, and When Passed to Functions