Imagine I have a bag of 26 scrabble tiles - one for each letter in the English alphabet.
My goal is to create an array of all possible strings up to n
letters long. Say n=3
.
Constraints:
- Letters must always be in alphabetical order (
ABC
, notCBA
; combinations, not permutations) - Strings must be <=
n
letters long (allow algorithm to break out of any loops at a given length) - Letters may not repeat (
A
, notAA
)
How can I most efficiently generate this array in PHP?
In other words, how can I avoid brute force looping through all possible combinations and filtering out those that don't match the rules above?
If my alphabet only contained 3 letters — $alphabet = range('a','c');
— I'd expect output of an array of 7 items (3C1+3C2+3C3): [A,B,C,AB,AC,BC,ABC]
.
If my alphabet only contained 4 letters — $alphabet = range('a','d');
— I'd expect output of an array of 15 items (4C1+4C2+4C3+4C4): [A,B,C,D,AB,AC,AD,BC,BD,CD,ABC,ABD,ACD,BCD,ABCD]
. But if I wanted to limit to only strings <= 3
letters long, then I would ignore ABCD
resulting in only 14 items (4C1+4C2+4C3).
$alphabet = range('a','z');
print_r(generate_strings($alphabet,1));
// expected output: A,B,C,...Z
print_r(generate_strings($alphabet,2));
// expected output: A..Z, AB..AZ, BC..BZ, CD, ..YZ
print_r(generate_strings($alphabet,3));
// expected output: A..Z, AB..YZ, ABC..XYZ
print_r(generate_strings($alphabet,10));
// expected output: A .. JKLMN .. AGKQRZ .. QRSTUVWXYZ
// ^ ^ ^10 character max, no repeats
// | still alphabetical order
// alphabetical order
function generate_strings($alphabet,$max_word_length) {
// how can I efficiently generate this array
// without brute force looping through all of
// the invalid and duplicate items like AA and CBA?
return $array_of_all_possible_strings;
}