简体   繁体   中英

Trying to generate 9 digit numbers with each unique digits in Java

I am trying to generate all permutations of 9 digit numbers with each digit from 1 to 9 used exactly once with no repeats. for example, 123456789, 132456789, 987654321 etc.... The reason i tagged this question with recursion is because I believe thats how I have to solve this question but I'm not sure how to do that in Java

The program should return a list of int arrays.

List<int[]> list = new ArrayList<int[]>();
int[] values = {1,2,3,4,5,6,7,8,9};
int count=0;
int count2=0;
int count3=1;

while(count2<9*8*7*6*5*4*3*2) {
    for(int i =1;i<values.length-1;i++) {
        if (count<8*7*6*5*4*3*2) {
            Integer toMove = values[i];
            values[i]=values[i+1];
            values[i+1]=toMove;
            count++;
        } else if (count>=8*7*6*5*4*3*2&&count3<9) {
            values[0]=1;
            values[1]=2;
            values[2]=3;
            values[3]=4;
            values[4]=5;
            values[5]=6;
            values[6]=7;
            values[7]=8;
            values[8]=9;
            Integer toMove = values[0];
            values[0]=values[count3];
            values[count3]=toMove;
            count=1;
            count3++;
            i=0;
        }

        count2++;
        list.add(values);
    }

Hope this is what you were looking for

//Initialize List
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

//Shuffle List      
Collections.shuffle(numbers);

//Obtain Array
Integer randomizedArray[] = numbers.toArray(new Integer[0]);

//Print Array
System.out.println(Arrays.toString(randomizedArray));

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