This is a particular variation of an oft-repeated question, but try as I might, I couldn't find this exact situation anywhere on Stack Overflow.
Long story short, I want to take an array like this:
$days[0] = 'Monday';
$days[1] = 'Tuesday';
$days[2] = 'Thursday';
($days could contain any number and combination of the five work days of the week.)
And then, given a particular value of $numberOfDays
(which, of course, has to be at least 1 and not more than the count of $days
), I'd like an array containing all the possible combinations of $days with $numberOfDays number of days.
For example:
$days[0] = 'Monday';
$days[1] = 'Tuesday';
$days[2] = 'Thursday';
$numberOfDays = 2;
$dayCombinations = getDayCombinations($days, $numberOfDays);
Output:
$dayCombinations[0] = array("Monday", "Tuesday");
$dayCombinations[1] = array("Monday", "Thursday");
$dayCombinations[2] = array("Tuesday", "Thursday");
Note that these are combinations, not permutations, so order doesn't matter.
If it helps, I found this function here: It works well, but includes repetitions and is based off of a string instead of an array (that last part is workable, not a big deal, but the repetitions part really messes it up for me).
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);
}
UPDATE: I've tried to wrap the line assigning $new_combinations
with a conditional to help; this has had no effect at all, though I'm not sure why. All of the combinations still come through, even those with repetitions.
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) {
if (strpos($combination, $char) === FALSE) {
echo "Char $char not found in Combination $combination<br>";
$new_combinations[] = $combination . $char;
}
}
}
# call same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
The output in there returns oddities like:
Char 2 not found in Combination 2
Char 3 not found in Combination 23
And so on.
Thanks for the help!
Alex