The problem you suggest is very similar to this Leetcode Challenge. The idea is to use Backtracking
Psuedo PsedoCode :
result := string Array
CartesianProduct(rowIndex, ArrayList, stringSoFar):
if rowIndex equal ArrayList.size:
Add stringSoFar to result
return
for(eachItem in ArrayList[rowIndex])
CartesianProduct(rowIndex +1 , ArrayList, stringSoFar + eachItem)
return
This is a workhorse which does all the computation and can be called like CartesianProduct(0, list of Array to be multiplied, "")
Suppose your ArrayList = [['A'], ['C', 'D']]
. And CP
be CartesianProduct
CP(0, AL, "")
(Take 'A')/
/
CP(1, AL, "A") (stringSoFar becomes 'A')
(Take C) / \(Take 'D'.Second Iteration with second array['C', 'D'])
/ \
CP(2, AL, "AC") CP(2, AL, "AD")
/ \
rowIndex equal size. rowIndex equals listSize i.e No more list to look
Add "AC" and return Add stringsoFar ("AD") to result and rerturn
My solution to the Leetcode problem(but in C++). Hopefully it'll give you some idea to write in PHP
class Solution {
public:
map<char, vector<string>> values {
{'2', vector<string>{"a", "b", "c"}},
{'3', vector<string>{"d", "e", "f"}},
{'4', vector<string>{"g", "h", "i"}},
{'5', vector<string>{"j", "k", "l"}},
{'6', vector<string>{"m", "n", "o"}},
{'7', vector<string>{"p", "q", "r", "s"}},
{'8', vector<string>{"t", "u", "v"}},
{'9', vector<string>{"w", "x", "y", "z"}}
};
vector<string> answer;
void doComb(int index, string digits, string sofar)
{
if(index == digits.size())
{
if(sofar != "")
{
answer.push_back(sofar);
}
return;
}
for(auto lett : values[digits[index]])
{
doComb(index + 1, digits, sofar + lett);
}
return;
}
vector<string> letterCombinations(string digits) {
doComb(0, digits, "");
return answer;
}
};