0

The following is no homework. I'm just trying to write my own permutation code. I have an idea but I have problems in writing this idea as code.

As example the input is myArray={1,2,3};

Then the output is supposed to be:

1 2 3
2 1 3
2 3 1
3 2 1
3 1 2
1 3 2

I figured out it's possible by switching the first element with second, then switch second with third (however not entirely possible, but I know I need this).

That's why my question is how can I do this in Java?

I have 1 2 3 and I want switch first element with second, so I get 2 1 3. Print this. Now I want switch second element with third, I get 2 3 1, print it. Repeat n! times where n is myArray length.

I tried to do this with the following code but it seems like I'm far away from it :(

public class Test{
    public static void main(String[] args){
        int[] myArray = {1,2,3};

        for(int x=0; x<6; x++){
            for(int i=0; i<myArray.length-1; i++){
                int temp=myArray[i];
                myArray[i]=myArray[i+1];
                myArray[i+1]=temp;
            }
            for(int i=0; i<myArray.length; i++){
                System.out.print(myArray[i]+" ");
            }
            System.out.println("");
        }
    }
}
Output:
2 3 1 
3 1 2 
1 2 3 
2 3 1 
3 1 2 
1 2 3 
2

1 Answer 1

1

I'm not sure if I understood correctly though.

public static void main(String[] args) {
    int[] myArray = {1, 2, 3};
    for (int i = 0; i < 6; i++) {
        print(myArray);
        int temp = myArray[i % myArray.length];
        myArray[i % myArray.length] = myArray[(i + 1) % myArray.length];
        myArray[(i + 1) % myArray.length] = temp;
    }
}

private static void print(int[] array) {
    for (int anArray : array) {
        System.out.print(anArray + " ");
    }
    System.out.println("");
}

EDIT:

I noticed, there is a wrong order, so it should be better:

public static void main(String[] args) {
    int[] myArray = {1, 2, 3};

    for (int i = 0; i < 6; i++) {
        int idx = i % (myArray.length - 1);
        print(myArray);
        int temp = myArray[idx];
        myArray[idx] = myArray[idx + 1];
        myArray[idx + 1] = temp;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.