mercredi 11 décembre 2019

All possible combinations of r elements in a given array of size n with conditions

I have this code which gives me all the possible combinations of the four elements of my array {'a', 'b', 'c', 'd'} of size 4.

Everything's working, but I need to add some specifications to my code and I can't get my head around how to do it.

The two conditions I have to add are : ‘b’ always have to be followed by ‘a’ in a string and one string can't have both the char ‘d’ and the char ‘a’.

    static void printAllKLength(char[] set, int k) { 
        int n = set.length;  
        printAllKLengthRec(set, "", n, k); 
    } 

    static void printAllKLengthRec (char[] set,  
                                   String prefix,  
                                   int n, int k) 
    { 

        if (k == 0)  {
            System.out.println(prefix); 
            return; 
        } 
        for (int i = 0; i < n; ++i) {
            String newPrefix = prefix + set[i];  
            printAllKLengthRec(set, newPrefix,  
                                    n, k - 1);  
        } 
    } 

    public static void main(String[] args) {
        char[] set1 = {'a', 'b', 'c', 'd'}; 
        int k = 4; 
        printAllKLength(set1, k); 


    } 
    } 

Aucun commentaire:

Enregistrer un commentaire