Search code examples
javaarraysword-wrap

Java Array Wrap Around


Hi i wondering to on how to wrap an array

for example take the array below:

|00  01  02  03  04  05  06  07|

say i wanted to move everything right, to get to this:

|07  00  01  02  03  04  05  06|

how do i do this without losing any of data?

to move things to the right i am currently using this code:

public void transform(IFrame frame) {

    char tempImage;

    for (int i = 0; i < frame.getNumRows(); i++) {
        for (int j = 0; j < frame.getNumRows(); j++) {

            tempImage = frame.getChar(i,j);

            frame.setChar(i+1, j, tempImage);
}

essentially what i want the code to do in very basic terms is:

  • go through each row/column (the frame.getNumRows , as the frame is square the rows/columns are the same

  • get the char value of i and j from the frame

-with that frame, set the frame char value of i and j to be i+1 whilst keeping j the same

-with the character to be set being the temp image

UPDATE

I have implemented this method and changed it from the previous one posted, below is the updated code:

public void transform(IFrame frame) {

        char constantImage;

        for (int i = 0; i < frame.getNumRows(); i++) { //go through each row/column
            for (int j = 0; j < frame.getNumRows(); j++) {

                constantImage = frame.getChar(i, j);

                TransformFrames.add(constantImage);

                Collections.rotate(Arrays.asList(TransformFrames), 1);


                for (Character f : TransformFrames) {
                    frame.setChar(i, j, f);
                }
            }
        }
    } 

TransformFrames is a character array list.

Through debugging i can see that the correct data is being added to the array list, and i hope being moved across however i am unable to see this happening as the gui is not updating once this method is called - any suggestions why or how to fix??

Thanks


Solution

  • An easy way is Collections.rotate:

    Collections.rotate(Arrays.asList(array), 1);