本文介绍了如何从两个数组中获取所有可能的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组:
String[] operators = {"+", "-", "*"}; int[] numbers = {48, 24, 12, 6};我想以这样的字符串格式获取所有可能的组合:
And I want to get all possible combination in a String format like this:
48+24+12+6 48+24+12-6 48+24+12*6 48+24-12+6 48+24-12-6 48+24-12*6 .......... 48*24*12*6这是我尝试过的:
for (int i = 0; i < operators.length; i++) { System.out.println(numbers[0] + operators[i] + numbers[1] + operators[i] + numbers[2] + operators[i] + numbers[3]); }但它仅打印:
48+24+12+6 48-24-12-6 48*24*12*6如何解决这个问题?
这不是重复的,因为我不想获取每两对数据,我想获取4对中的每个组合.重复项不同.
This is not a duplicate because I don't want to get every two pairs of data, I want to get every combination in 4 pairs. The duplicate is different.
推荐答案使用三重循环:
for (int i=0; i < operators.length; ++i) { for (int j=0; j < operators.length; ++j) { for (int k=0; k < operators.length; ++k) { System.out.println(numbers[0] + operators[i] + numbers[1] + operators[j] + numbers[2] + operators[k] + numbers[3]); } } }您本质上想获取运算符向量的叉积(如果它是向量).在Java中,这转化为三重嵌套的循环集.
You essentially want to take the cross product of the operators vector (if it were a vector). In Java, this translates to a triply-nested set of loops.
更多推荐
如何从两个数组中获取所有可能的组合?
发布评论