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 algorithm to generate all combinations of a specific size from a single set
I would use a recursive function. Here's a (working) example with comments. Hope this works for you!
function sampling($chars, $size, $combinations = array()) {
# if it's the first iteration, the first set
# of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
# we're done if we're at size 1
if ($size == 1) {
return $combinations;
}
# initialise array to put new values in
$new_combinations = array();
# loop through existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
# call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
// example
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);
/*
array(9) {
[0]=>
string(2) "aa"
[1]=>
string(2) "ab"
[2]=>
string(2) "ac"
[3]=>
string(2) "ba"
[4]=>
string(2) "bb"
[5]=>
string(2) "bc"
[6]=>
string(2) "ca"
[7]=>
string(2) "cb"
[8]=>
string(2) "cc"
}
*/
Generate all possible combinations with PHP
This is probably not very efficient but it will get the job done:
<?php
$alph = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
$a = array();
foreach( $alph as $l1 )
{
$a[0] = $l1.'10';
foreach( $alph as $l2 )
{
$a[1] = $l2.'1';
foreach( $alph as $l3 )
{
$a[2] = $l3.'18';
foreach( $alph as $l4 )
{
$a[3] = $l4.'4';
foreach( $alph as $l5 )
{
$a[4] = $l5.'9';
foreach( $alph as $l6 )
{
$a[5] = $l6.'14';
foreach( $alph as $l7 )
{
$a[6] = $l7;
foreach( $alph as $l8 )
{
$a[7] = ' '.$l8; // your example shows a space, not sure if that was intentional
// $line = implode( '', $a )."\r\n";
// Write $line to a file
}
}
}
}
}
}
}
}
Sample output:
A10A1A18A4A9A14A A
A10A1A18A4A9A14A B
A10A1A18A4A9A14A C
A10A1A18A4A9A14A D
A10A1A18A4A9A14A E
A10A1A18A4A9A14A F
A10A1A18A4A9A14A G
A10A1A18A4A9A14A H
A10A1A18A4A9A14A I
A10A1A18A4A9A14A J
A10A1A18A4A9A14A K
A10A1A18A4A9A14A L
A10A1A18A4A9A14A M
A10A1A18A4A9A14A N
A10A1A18A4A9A14A O
A10A1A18A4A9A14A P
A10A1A18A4A9A14A Q
A10A1A18A4A9A14A R
A10A1A18A4A9A14A S
A10A1A18A4A9A14A T
A10A1A18A4A9A14A U
A10A1A18A4A9A14A V
A10A1A18A4A9A14A W
A10A1A18A4A9A14A X
A10A1A18A4A9A14A Y
A10A1A18A4A9A14A Z
A10A1A18A4A9A14B A
A10A1A18A4A9A14B B
A10A1A18A4A9A14B C
A10A1A18A4A9A14B D
A10A1A18A4A9A14B E
A10A1A18A4A9A14B F
A10A1A18A4A9A14B G
A10A1A18A4A9A14B H
A10A1A18A4A9A14B I
A10A1A18A4A9A14B J
A10A1A18A4A9A14B K
A10A1A18A4A9A14B L
A10A1A18A4A9A14B M
A10A1A18A4A9A14B N
A10A1A18A4A9A14B O
A10A1A18A4A9A14B P
A10A1A18A4A9A14B Q
A10A1A18A4A9A14B R
A10A1A18A4A9A14B S
A10A1A18A4A9A14B T
A10A1A18A4A9A14B U
A10A1A18A4A9A14B V
A10A1A18A4A9A14B W
A10A1A18A4A9A14B X
A10A1A18A4A9A14B Y
A10A1A18A4A9A14B Z
A10A1A18A4A9A14C A
A10A1A18A4A9A14C B
A10A1A18A4A9A14C C
A10A1A18A4A9A14C D
A10A1A18A4A9A14C E
A10A1A18A4A9A14C F
A10A1A18A4A9A14C G
A10A1A18A4A9A14C H
Get all possible combinations without duplicates
I hope below function work as per your expected output :
function get_array_combination($arr) {
$results = array(array( ));
foreach ($arr as $values)
foreach ($results as $combination)
array_push($results, array_merge($combination, array($values))); // Get new values and merge to your previous combination. And push it to your results array
return $results;
}
$set = array('1', '2', '3', '4');
$final_array = get_array_combination($set);
echo "<pre>";
print_r(array_values(array_filter($final_array))); // Removed blank entry from array and re indexing array keys.
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 ) )
PHP: How do you generate all possible combinations of values in an array?
Here's another way.
This function increments in base( [number of elements in array] )
and uses the strtr function to swap out the characters for strings.
function everyCombination($array) {
$arrayCount = count($array);
$maxCombinations = pow($arrayCount, $arrayCount);
$returnArray = array();
$conversionArray = array();
if ($arrayCount >= 2 && $arrayCount <= 36)
{
foreach ($array as $key => $value) {
$conversionArray[base_convert($key, 10, $arrayCount)] = $value;
}
for ($i = 0; $i < $maxCombinations; $i++) {
$combination = base_convert($i, 10, $arrayCount);
$combination = str_pad($combination, $arrayCount, "0", STR_PAD_LEFT);
$returnArray[] = strtr($combination, $conversionArray);
}
return $returnArray;
}
echo 'Input array must have between 2 and 36 elements';
}
Then ...
print_r(everyCombination(array('a', 'b', 'c', 'd')));
This also seems to be significantly faster than the recursive example below.
Using microtime() on my server this code runs in 0.072862863540649 seconds
The recursive example below takes 0.39673089981079 seconds.
138% faster!
PHP take all combinations
OK, here's your code (and btw, thanks for posting such an interesting and challenging problem - at least for me... :-)) - using recursion for all possible permutations (by N) given an array of elements)
Code :
<?php
function permutations($arr,$n)
{
$res = array();
foreach ($arr as $w)
{
if ($n==1) $res[] = $w;
else
{
$perms = permutations($arr,$n-1);
foreach ($perms as $p)
{
$res[] = $w." ".$p;
}
}
}
return $res;
}
// Your array
$words = array('cat','dog','fish');
// Get permutation by groups of 3 elements
$pe = permutations($words,3);
// Print it out
print_r($pe);
?>
Output :
Array
(
[0] => cat cat cat
[1] => cat cat dog
[2] => cat cat fish
[3] => cat dog cat
[4] => cat dog dog
[5] => cat dog fish
[6] => cat fish cat
[7] => cat fish dog
[8] => cat fish fish
[9] => dog cat cat
[10] => dog cat dog
[11] => dog cat fish
[12] => dog dog cat
[13] => dog dog dog
[14] => dog dog fish
[15] => dog fish cat
[16] => dog fish dog
[17] => dog fish fish
[18] => fish cat cat
[19] => fish cat dog
[20] => fish cat fish
[21] => fish dog cat
[22] => fish dog dog
[23] => fish dog fish
[24] => fish fish cat
[25] => fish fish dog
[26] => fish fish fish
)
HINT : By permutations($words,2)
, you'll be able to get exactly what you wanted...
Efficient PHP algorithm to generate all combinations / permutations of inputs
Give this a shot:
<?php
$chars = array('a','b','c');
$count = 13;
$generator = genCombinations($chars,$count);
foreach ($generator as $value) {
// Do something with the value here
echo $value;
}
function genCombinations($values,$count=0) {
// Figure out how many combinations are possible:
$permCount=pow(count($values),$count);
// Iterate and yield:
for($i = 0; $i < $permCount; $i++)
yield getCombination($values, $count, $i);
}
// State-based way of generating combinations:
function getCombination($values, $count, $index) {
$result=array();
for($i = 0; $i < $count; $i++) {
// Figure out where in the array to start from, given the external state and the internal loop state
$pos = $index % count($values);
// Append and continue
$result[] = $values[$pos];
$index = ($index-$pos)/count($values);;
}
return $result;
}
It is a state-based fixed-length combination generator that should hopefully fit the bill. It will only accept arrays and will return combinations of the array items, regardless of what is actually stored in the array.
How to get all the combinations of an array in php without functions
Getting all combinations works on the principle of next permutation. This basically means it follows the below steps:
The input needs to be sorted as the starting combination. This eases out the calculations and produces a uniform result. Below snippet does use
sort()
inbuilt function but you can roll out for your own sort function(which I leave it to you as an exercise).For a next permutation, we need to find 2 digits where smaller digit occupies an MSB place over the larger digit.
Once found, we swap those 2 digits and reverse the array from MSB + 1 position. This reverse operation is to get next smallest lexicographic combination. If not performed, you will miss out on some needed in-between combinations.
The logic stops when the digits get sorted in non-increasing manner yielding the last combination possible.
Snippet:
<?php
function getCombinations($numbers){
sort($numbers); // create your own custom function for sort.
$result = [ $numbers ];
do{
$x = $y = -1;
for($i = count($numbers) - 1; $i >= 0; --$i){
for($j = $i - 1; $j >= 0; --$j){
if($numbers[ $j ] < $numbers[ $i ] && ($y === -1 || $y < $j)){
$x = $i;
$y = $j;
}
}
}
if($x !== -1){
swap($numbers, $x, $y);
reverse($numbers, $y + 1, count($numbers) - 1);
$result[] = $numbers;
}
}while($x != -1);
return $result;
}
function reverse(&$numbers, $left, $right){
while($left < $right){
swap($numbers, $left++, $right--);
}
}
function swap(&$numbers, $x, $y){
$temp = $numbers[ $x ];
$numbers[ $x ] = $numbers[ $y ];
$numbers[ $y ] = $temp;
}
print_r(getCombinations([1,2,3,4]));
Online Demo
Related Topics
Adding a Namespace When Using Simplexmlelement
How to Add Namespace to an Attribute with PHP's Simplexml
Warning: Array_Combine(): Both Parameters Should Have an Equal Number of Elements
Get the Hierarchy of a Directory with PHP
Jquery: Running Ajax Locally Without a Webserver
Convert Clickable Anchor Tags to Plain Text in HTML Document
Which MySQL Datatype to Use for an Ip Address
Get Characters After Last/In Url
Can PHP Detect If Its Run from a Cron Job or from the Command Line
How to Override Built-In PHP Function(S)
How to Join Two Tables with Ssp.Class.Php
$_Post Is Empty After Form Submit
How to Select Default Value of a Field
How to Reverse a Unicode String
PHP and MySQLi - Cannot Pass Parameter 2 by Reference In