从给定范围的阵列中获取六个独特组合的集合

时间:2016-08-31 09:25:15

标签: arrays random

我确实有问题,我有1-49的数字,现在这里的问题是如何从给定的样本中获得最大六个随机集合数。像

int[] a1 = { 1, 2, 3 ,5,6,7 ... 49};

我可以从1到49之间的一个大数组获得多少个数字或数组的唯一组合,如下所示

1,2,3,4,5,6
2,1,4,5,8,9
2,1,0,2,4,5
................

我想要得到的是最大输出或可能的唯一数组的数量,长度为6我可以得到。说实话,我试过写一个循环读取数组,但如何捕获六个随机数字是我卡住的地方我可以继续下去

      for(int x=0;<a1.length;x++)
      {
          // here i believe i must turn the captured information 
         // into a muti dimentional array to cpature like '1,2,3,4,5,6' but how. am stuck
       }

2 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,那么您需要的是binomial coefficient n! / k! (n - k)!,在这种情况下49! / (6! * (49 - 6)!) = 13983816。如果您想知道的唯一事情是可能的组合数量,则无需编写代码。

如果你真的想列出所有这些,你需要一点耐心。实现这一目标的一种方法是通过递归方法:

public class NOverK {

    private static final int[] numbers = new int[6];
    private static final int MAX = 49;

    private static void output() {
        System.out.println();
        for (int n : numbers) {
            System.out.print(n + " ");
        }
    }

    private static void allCombinations(int x, int start) {
        if (x > 0) {
            for (int i = start; i <= MAX; i++) {
                numbers[numbers.length - x] = i;
                allCombinations(x - 1, i + 1);
            }
        } else {
            output();
        }
    }

    public static void main(String[] args) {
        allCombinations(6, 1);
    }
}

答案 1 :(得分:1)

This question has been asked at Stack Overflow a few times in the past. For example, look at this answer:

Click here: Algorithm to return all combinations of k elements from n

The answers to this question contain numerous solutions of your question in different programming languages (Java, Python, C, C# etc.), too. Check out or adjust a solution that meets your requirements.

You can search for other questions/answers in Stack Overflow (search field in upper right corner) with keywords

[algorithm] [combinations]

A Google search would lead to numerous solutions of your question, too. Try with keywords as follows:

java algorithm combinations without repetition

or

c# algorithm combinations without repetition