samedi 4 janvier 2020

All possible combinations of a,b,c,d (lenght 4) with conditions (java)

So I need this algorithm to work but I can't seem to find where the problem is... I need to print all the possible combinaison of [a,b,c,d] (with a lenght of 4) with some condition (already in the algorithm). So what am I missing ? I'm still a begginer in Java, so thanks a lot for your help !

public class Test {

//Method saying that 'a' always have to follow 'b'
public static boolean aFollowsB(String s) {
      char[] set1 = s.toCharArray();

      for (int i = 0; i < set1.length; i++) {
        // If B is the last char, A can't possilby follow
        if (i == set1.length - 1) {
          if (set1[i] == 'b') { return false; }
        // Else if we encounter B, make sure next is an A
        } else {
          if (set1[i] == 'b') {
            if (set1[i+1] != 'a') { return false; }
          }
        }
      }

      return true;
    }

//Method saying that we can't have 'a' and 'd' in the same string
    public static boolean hasOnlyAOrD(String s) {
      char[] set1 = s.toCharArray();

      boolean hasA = false;
      boolean hasD = false;

      for (int i = 0; i < set1.length; i++) {
        if (set1[i] == 'a') {
          hasA = true;
        } else if (set1[i] == 'd') {
          hasD = true;
        }
      }

      if (hasA && hasD) {
        return false;
      }

      return true;
    }

//Method printAllKLength to print all possible strings of k lenght
    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); 
              System.out.println(prefix);
            return; 

        } 
        for (int i = 0; i < n; ++i) {
            String newPrefix = prefix + set[i];  
            printAllKLengthRec(set, newPrefix,  
                                    n, k - 1);  
        } 
    } 
    //Method to print with the conditions
    public static void main(String[] args) {
        char[] set1 = {'a', 'b', 'c', 'd'}; 
        int k = 4; 
        if (aFollowsB(set1) && hasOnlyAOrD(prefix)) {
            printAllKLength(set1, k); 
            }

}}

Aucun commentaire:

Enregistrer un commentaire