0

I am looking for a method in java to have all combinations of the elements of x taken m at a time.

please note all proposed algorithms (see the below link and code) so far just print list of combination with using a recursive function strategy and don't save the results in a array

for instance if str[] data={"a","b","c","d"} with m=2 (please note: data and m are arguments for the method)

the method returns an array :

(a,b
 a,c
 a,d
 b,c
 b,d
 c,d)

Again the below code just print them and not save them in an array:

Short java solution:

import java.util.Arrays;

public class Combination {
    public static void main(String[] args){
        String[] arr = {"A","B","C","D","E","F"};
        combinations2(arr, 3, 0, new String[3]);
    }

    static void combinations2(String[] arr, int len, int startPosition, String[] result){
        if (len == 0){
            System.out.println(Arrays.toString(result));
            return;
        }       
        for (int i = startPosition; i <= arr.length-len; i++){
            result[result.length - len] = arr[i];
            combinations2(arr, len-1, i+1, result);
        }
    }       
}
Community
  • 1
  • 1
  • Saving the results in an array is not very realistic unless you're not going to extend beyond the scope of your example. If I understand you correctly you'd have to return an array with `x.length` choose `m` pairs, which is factorial growth. What is the proposed purpose for this? – Kyle Travis Mar 04 '14 at 20:45
  • Why not replace the `println` with a line that adds `result` to a list of some sort? – tcooc Mar 04 '14 at 20:46
  • Yes, that would seem to satisfy your requirement. You can even used a fixed length array, knowing how many combinations you'll get ahead of time. – Kyle Travis Mar 04 '14 at 20:47
  • @Kyle Travis: I want to use this result a core to do more computation. – user3362866 Mar 04 '14 at 20:48

0 Answers0