简体   繁体   中英

How to find all possible numbers with a Recursion method

i want to write a Recursion method that prints all possible arrangements for these numbers , the integers 1 to 9

arranged randomly in a grid of three rows and three column.for example :

6   2   1

5   4   7

3   9   8

sorry i don't have any code , because it's very hard to me.

public class Test {

public static void main (String[] args){
     String x = "123456789";
    System.out.println(test(x,0));


}
public static String test(String x , int y){

    if(x.length()==1)return "";

    return x.charAt(y)+test(x.substring(y),y);
}   

pass values ​​to an array, randomize and create a loop to generate the matrix. loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array

int j = 0;
 for( int i = 0; i <= YOURARRAY.length(); i++)
   {
System.out.println(   i POSITIONOFARRAY   );
j+1
   }

There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:

public static void main(String[] args) {
    nextPermutation(new int[9], 0, new boolean[9]);
}

public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
    if(index == perm.length) {
        //the permutation is complete
        //you can store it or print it
    } else {

        for(int i = 0 ; i < alreadyUsed.length ; i++) {
            if(alreadyUsed[i]) continue;

            perm[index] = i+1;

            boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
            newAlreadyUsed[i] = true;
            nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
        }
    }
}

This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.

Note that it's important to pass copies of perm and alreadyUsed , otherwise you will just pass the same array and overwrite previous permutations.

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