I have an 2D-array like this in java
transmission communication tv television
approach memorycode
methodact
开发者_高级运维
I need to get all combinations like:
{transmission,approach,methodact},{transmission,memorycode,methodact},{communication,approach,methodact},...
Can someone provide an example that will work for nXn arrays, even if it has only two rows?
This should do the trick:
static Set<List<String>> allComb(String[][] opts) {
Set<List<String>> results = new HashSet<List<String>>();
if (opts.length == 1) {
for (String s : opts[0])
results.add(new ArrayList<String>(Arrays.asList(s)));
} else
for (String str : opts[0]) {
String[][] tail = Arrays.copyOfRange(opts, 1, opts.length);
for (List<String> combs : allComb(tail)) {
combs.add(str);
results.add(combs);
}
}
return results;
}
This code in JavaScript can help you:
var sampleArray = [["transmission","communication","tv","television"], ["approach","memorycode"], ["methodact"]];
var GetAllCombinations = function(array2d) {
var ret=[];
var fn = function(arr,index,cur)
{
var ret = [];
for (var i=0; i<arr[index].length; i++)
{
var x = cur.slice(0);
x.push(arr[index][i]);
if (index == arr.length-1)
ret.push(x);
else
ret = ret.concat(fn(arr,index+1,x));
}
return ret;
};
return fn(array2d,0,[]);
} console.log(GetAllCombinations(sampleArray));
It builds all combinations starting with a given array, iterates over all the options for that level and call it recursively, then concatenate it with the result.
精彩评论