对象数组的每个组合

ZBS*_*pts 3 java recursion combinations

基本上,我有一个包含25个不同人的数组,我需要选择其中5个人,并且每个组合都可以,而不使用同一个人的重复项.

我能想到的唯一合乎逻辑的方法是使用5个for循环并检查是否已经使用过人,尽管这看起来似乎有一个更好的方法涉及递归.

如果有人可以提供帮助,我将非常感激.

这是我班上的一个例子;

public class Calculator {

    final Person[] people = new Person[25]; //Pretend we have filled in this info already

    public List<Group> generateList()
    {
        final List<Group> possible = new ArrayList<>();
        for (int a = 0; a < 25; a++)
        {
            for (int b = 0; b < 25; b++)
            {
                for (int c = 0; c < 25; c++)
                {
                    for (int d = 0; d < 25; d++)
                    {
                        for (int e = 0; e < 25; e++)
                        {
                            final Group next = new Group();
                            next.set = new Person[] {
                                people[a],
                                people[b],
                                people[c],
                                people[d],
                                people[e]
                            };
                            possible.add(next);
                        }
                    }
                }
            }
        }
        return possible;
    }



    class Group {

        Person[] set = new Person[5];

    }

    class Person {

        String name;
        int age;

    }

}
Run Code Online (Sandbox Code Playgroud)

但是我不确定这样做的最好方法,如果这样就能得到所有组合.我也知道这里没有重复检查,我会通过检查来做;

如果(b == a)继续;

等等.

我将不胜感激任何帮助.

Sim*_*mon 9

一种可能性是使用组合库,例如:http://code.google.com/p/combinatoricslib/.

// Create the initial vector
   ICombinatoricsVector<String> initialVector = Factory.createVector(
      new String[] { "red", "black", "white", "green", "blue" } );

   // Create a simple combination generator to generate 3-combinations of the initial vector
   Generator<String> gen = Factory.createSimpleCombinationGenerator(initialVector, 3);

   // Print all possible combinations
   for (ICombinatoricsVector<String> combination : gen) {
      System.out.println(combination);
   }
Run Code Online (Sandbox Code Playgroud)

该示例来自项目页面(请参阅链接).将它转移到您的用例应该很容易.