PeopleSoft Adoption Made Smooth & Simple!
On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool. Claim Your Free WalkMe Account Now
Become a Premium Member and unlock a new, free course in leading technologies each month.
Add your voice to the tech community where 5M+ people just like you are talking about what matters.
<?php // RAY_combinations_all_ordered_subsets.php
error_reporting(E_ALL);
echo "<pre>";
// PROBLEM: FIND ALL ORDERED SUBSETS OF A CHARACTER SET
// EXAMPLE: IN "ABC" IT MUST FIND "A", "AB", "BA", ETC.
// FUNCTION TO GENERATE THE COMBINATIONS OF CHARACTERS IN A STRING.
// OUTPUT IS AN ARRAY OF COUNT = strlen() FACTORIAL
// ADAPTED FROM http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/
function string_combinations($str)
{
if (strlen($str) < 2) return array($str);
$combos = array();
$endpop = substr($str, 1);
// RECURSE
foreach (string_combinations($endpop) as $permutation)
{
$length = strlen($permutation);
for ($i = 0; $i <= $length; $i++)
{
$combos[] = substr($permutation, 0, $i) . $str[0] . substr($permutation, $i);
}
}
return $combos;
}
// GENERATE THE COMBINATIONS OF ELEMENTS IN A ONE-DIMENSIONAL ARRAY
function array_combinations($arr)
{
$return = array();
// GET THE NUMERIC KEY RANGE OF THE INPUT ARRAY
$str = implode('', range(0, count($arr)-1));
// GET THE KEY COMBINATIONS
$combos = string_combinations($str);
// ITERATE OVER THE COMBINATIONS
foreach ($combos as $combo)
{
$out = array();
while (strlen($combo))
{
$key = substr($combo,0,1);
$combo = substr($combo,1);
$out[] = $arr[$key];
}
$ndx = implode(NULL, $out);
$return[$ndx] = $out;
}
return $return;
}
// DEMONSTRATE THE CODE
$abc = 'ABCDEF';
$abc = str_split($abc);
$cnt = count($abc) - 1;
// GET ALL LARGEST COMBINATIONS IN ARRAY FORMAT
$out = array_combinations($abc);
$out = array_keys($out);
// REDUCE THE STRING LENGTHS TO FIND SMALLER COMBINATIONS
while ($cnt)
{
foreach ($out as $key)
{
$key = substr($key, 0, $cnt);
$key = str_split($key);
sort($key);
$key = implode(NULL, $key);
$new[$key] = $key;
}
$cnt--;
}
// WITH EACH OF THE REDUCED STRINGS, ADD ALL COMBINATIONS
foreach ($new as $abc)
{
$arr = array_combinations(str_split($abc));
$out = array_merge($out, array_keys($arr));
}
// SHOW THE WORK PRODUCT
sort($out);
echo "FOUND " . number_format(count($out)) . " COMBINATIONS";
echo PHP_EOL;
print_r($out);
If you are experiencing a similar issue, please ask a related question
Join the community of 500,000 technology professionals and ask your questions.