views:

122

answers:

4

Hi, I have a set of numbers {'1','13','25','32','49',...}, i want to calculate all possible combinations of this numbers of order k.

Esample1:

set = {'1','5','23','41,'54','63'};
k = 4;

Output1:

1 5 23 41
1 5 23 54
1 5 23 63
1 5 41 54
1 5 41 63
1 5 54 63
1 23 41 54
1 23 41 63
1 23 54 63
1 41 54 63
5 23 41 54
5 23 41 63
5 23 54 63
5 41 54 63
23 41 54 63

Example2:

set = {'a','v','f','z'};
k=3;

Output2:

a v f
a v z
a f z
v f z

in Java plaese.

Thank you!

+4  A: 

You should be able to find an appropriate algorithm in D.Knuth's The Art of Computer Programming, Volume 4, fascicle 3 - Generating All Combinations, which can be downloaded from his website.

milan
@milan +1 ;))))
Boris Pavlović
A: 
public static void main(String[] args)
{
    java.util.List<Character> chars = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h');
    int k = 4;

    java.util.List<java.util.List<String>> result = new ArrayList<List<String>>();

    for (int i = 0; i <= chars.size() - k; i++)
    {
        List<String> column = new ArrayList<String>();
        for (int j = i + k - 1; j < chars.size(); j++)
        {
            StringBuilder sb = new StringBuilder();
            for (int m = i; m < i + k - 1; m++)
            {
                sb.append(chars.get(m)).append(' ');
            }
            sb.append(chars.get(j));
            System.out.println(sb.toString());
            column.add(sb.toString());
        }
        result.add(column);
    }
    String[][] arrayResult = to2dMatrix(result);
    for (String [] c : arrayResult)
    {
        System.out.println(Arrays.toString(c));
    }
}

private static String[][] to2dMatrix(List<List<String>> input)
{
    String[][] result = new String[input.size()][];
    for (int i = 0; i < input.size(); i++)
    {
        String[] s = new String[0];
        result[i] = input.get(i).toArray(s);
    }
    return result;
}
Boris Pavlović
And if i would an Array of Array as output?
Sabino
@Sabino voilla, to an array of arrays
Boris Pavlović
Thank you so much!
Sabino
It doesn't work!I correct the code but the output is not right!
Sabino
could you post the input list and value for k?
Boris Pavlović
i post the output up
Sabino
A: 

Thank you Boris!

And if i would an String[total_comb][k] as output?

like this:

out = {{'1','2','3'}, {'1','2','4'}, {'1','3','4'},...}

Sabino
A: 

@boris

this is the output:

a b c e
a b c f
a b c g
a b c h
b c d e
b c d f
b c d g
b c d h
c d e f
c d e g
c d e h
d e f g
d e f h
e f g h
Sabino