简体   繁体   中英

My Java method is not printing anything - Print all possible subsets of a number without repetition

I wrote this code to print all possible subsets of permutation, without repetition, of a number (n) but I cannot figure out why nothing is printing ie- for n = 3, is should output: 123 132 213 231 312 321

Here is the code I wrote:

public static void printAllPerm(int n)  {

          int [] A = new int[n+1];
          printAllRec(n, 0, A);

       }

    public static void printAllRec(int n, int i, int [] A)  {

          if ( promising(i, A) ) {
            if(i == n){         
                for (int j = 1; j <= n; j++)
                   System.out.print(A[j] + "  ");
                System.out.println();
            }   

          else
          {
             for (A[1] = 1; A[1] <= n; A[1]++)  {
                A[i+1] = A[1];
                printAllRec(n, i+1, A);
             }

          }
       }

    }//void printAllRec(int n, int i, int [] A)


    public static boolean promising(int n, int [] myArray)
    {
        for ( int i = 1; i <= n; i++){
            for (int j = 1; j <= n; j++){
                if ( (i != j) && ( myArray[i] == myArray[j]) )
                    return false;
            }
        }

        return true;    
    }

*** The method promising simply checks if a number is repeated ie- 112 is not allowed, all numbers have to be different

Problem lies here

 if ( promising(i, A) )

Here you are passing 0 as i due to which promising function returns false and nothing gets printed.

In printAllRec(..) at A[i+1] = A[1] , your code always ends up with an array with the same number twice just before you call promising(..) thus your print statement never gets called.

Write some tests for printAllRec(..) so you can tweak it to do what you're after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM