如何从两个数组中获取所有可能的组合?

编程入门 行业动态 更新时间:2024-10-11 21:31:14
本文介绍了如何从两个数组中获取所有可能的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数组:

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.

更多推荐

如何从两个数组中获取所有可能的组合?

本文发布于:2023-11-22 02:02:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   组中   个数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!