1

I have a question tonight. I am trying to make a java program that will take an array and then print all combinations that array of n size. For example: the full array is abcd, I want combinations of 2, so ideally I'd want aa, ab, ac, ect.

This is my current code, all it seems to output is a, b, c, d, e, ect:

public class test2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Input Array:
        String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"  };
        int r = 3;
        int n = alphabet.length;
        //I need pairings of n (length) so like. 6/7/8

        //Make an array to temporarily store the data, and commit recursion
        print(alphabet, n, r);
    }
    public static String[] buildAlphabeticPassword(String[] alphabet, String[] data, int start, int end, int index, int r){
        if (index == r){
            for(int i=0; i <= r; i++){
                System.out.println(data[i]+" ");
                System.out.println("");
                return data;
            }
        }
        for( int n=start; n <= end && end-n+1 >= r-index; n++){
            data[index] = alphabet[n];
        buildAlphabeticPassword(alphabet, data, n+1, end, index+1, r);

        }
        return null;
    }
    public static void print(String[] alphabet, int n, int r){


    String data[] = new String[r];

    buildAlphabeticPassword(alphabet, data, 0, n-1, 0,r);
    }


}

I apologize if I'm missing something super duper obvious. Thank you for your time!

Patrick O
  • 49
  • 2
  • 10
  • This common problem is called "permutation" and has been discussed many times on Stack Overflow, for example: http://stackoverflow.com/questions/18681165/shuffle-an-array-as-many-as-possible/18879232#18879232 – Quasimodo's clone Mar 27 '16 at 05:44
  • Possible duplicate of [All possible combinations of a 2D array](http://stackoverflow.com/questions/11326038/all-possible-combinations-of-a-2d-array) – Jos Mar 27 '16 at 05:46
  • I think this is an exact duplicate of this question: http://stackoverflow.com/questions/35965501/algorithm-to-solve-npr-permutations-for-dummies/35966478 – Stefan Haustein Mar 27 '16 at 10:28

0 Answers0