将多个数组组合到另一个数组

时间:2017-09-20 03:06:30

标签: php algorithm

我想要像这样组合2个数组

示例1:

Arr1 = ['A','B','C'],
Arr2 = ['D','E']

将成为

Arr3 = [
  ['A','D'],['A','E'],['B','D'],['B','E'],['',''] ....
]

示例2:

Arr1 = ['A','B','C'],
Arr2 = ['D','E']
Arr3 = ['G','H']

将成为

Arr4 = [
  ['A','D','G'],['A','E','G'],['','',''].... 
]

任何想法或建议我算法都可以像这样非常感谢

2 个答案:

答案 0 :(得分:1)

简化版;按索引合并数组

$arr1 = range('a', 'b');
$arr2 = range('c', 'f');
$arr3 = range('g', 'k');
$arr4 = range('x', 'z');
$res  = array();

// $counter = 1;
// while ($counter <= 4) {
//   $array = "arr{$counter}";
//   funcIndexMerge($res, $$array);
//   $counter++;
// }

funcIndexMerge($res, $arr1);
funcIndexMerge($res, $arr2);
funcIndexMerge($res, $arr3);
funcIndexMerge($res, $arr4);
var_export($res);

function funcIndexMerge(&$res, $array) {
    foreach ($array as $ari => $val)  {
        if (!isset($res[$ari])) {
            $res[$ari] = array();
        }
        $res[$ari] = array_merge($res[$ari], array($val));
    }
 }

答案 1 :(得分:1)

您建议的问题与此Leetcode Challenge非常相似。我们的想法是使用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 

这是一个可以完成所有计算的主力,可以像CartesianProduct(0, list of Array to be multiplied, "")

一样调用

假设您的ArrayList = [['A'], ['C', 'D']]。并CPCartesianProduct

                 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 

我对Leetcode问题的解决方案(但在C ++中)。希望它能给你一些用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;
    }
};