在java中打印数字数组的所有组合
我有一个 int[10] 数组。 数组的每个槽必须在 [0,30] 范围内,我想生成所有组合。我该怎么做呢?也许很容易,但我有点卡住了 顺便说一句,我使用的方式:
int[] array=new int[10];
for (int i=0;i<array.length;i++){
for (int j=0;i<30;j++){
print(array);
}
}
但不打印所有组合。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要向该数组添加元素。第一个循环让您在内部访问变量 i,第二个循环让您访问 j,但要填充它,我首先更喜欢递归方式:
创建一个带有数组变量和索引的方法(下一个要填充的位置)大批)。然后在方法1中使用新数组和index = 0调用该方法
。检查索引是否已经超出数组范围。在这种情况下,打印数组并退出该方法
2.在所有其他情况下,添加一个从 0 到 30 的 for 循环,然后在内部将当前数字添加到位置“index”并再次调用该方法,给出您的数组和索引+1,
但我会尝试使用 less 的方法项目第一。可能需要一段时间才能打印所有
此处的 vb.net 语言示例。您不能直接复制粘贴它,但它可能有助于理解如何创建组合。
索引 0..9 是数组的填充,如果索引是 10 则数组已满,我们只会显示它。要么我们用 0 到 30 之间的任何数字填充每个槽,要么你保留一个列表来记住哪些数字仍然剩余(在排列中,你需要首先用所有允许的数字填充剩余列表!)
you need to add elements to that array. the first loop gives you in the inner access to a variable i, the second for j, but to fill it I would first prefer a recursive way:
create a method with variables for your array and an index (which location to fill next in the array). Then call the method with a new array and index = 0
in the method 1. check if the index is already out of the array range. in that case print the array and exit the method
2. in all other cases, add a for loop from 0 to 30, and inside, add the current number to the location 'index' and call the method again, giving your array and index+1
but i would try that method with less items first. May take a while to print all
Here an example in vb.net language. You can not directly copy paste it, but it may help to understand how to create the combinations.
index 0..9 is t ofill array, if index is 10 then the array is full and we will only show it. Either we fill every slot with any number between 0 and 30, or you keep a list to memorize which numbers are still remaining (in the Permutations you need to fill the remaining list with all allowed numbers first!)
以下是 Kenneth H. Rosen 描述的算法,离散数学及其应用,第二版(纽约:McGraw-Hill,1991),第 284-286 页:CombinationGenerator - Java(链接已更新)
享受,
Here's an algorithm described by Kenneth H. Rosen, Discrete Mathematics and Its Applications, 2nd edition (NY: McGraw-Hill, 1991), pp. 284-286 : CombinationGenerator - Java (link updated)
Enjoy,