0

I want to make an array from something like this:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

To this:

{6, 5, 4, 3, 2, 1, 0, 13, 12, 11, 10, 9, 8, 7, 20, 19, 18, 17, 16, 15, 14}

But I'm clueless how. I think this method can serve as a good alternative to the code I plan to do. (I'm using Dr. Java so no imported files BTW)

for an integer array called integer[]:

    (for j = 0; j < 3; j++) {
            (for k = 0; k = 6; k++) {
                int newj = j+1;
                int array = integer[k*newj];
                integer [k*newj] = integer[6 - k*newj -1];
                integer[6 - k*newj - 1] = array;
            }
     }

But this doesn't work.

Any advice? It's not part of an assignment, but it's part of an exam that will happen within a week and I want to be sure of this.

3
  • Try changing the k = 6 to k <= 6. Also, your for syntax is wrong, it should be for (j = 0; j < 3; j++), i.e., for outside the parens. Commented Oct 26, 2013 at 23:52
  • Plus, instead of having the newj, you can just have j iterate from 1 to 3 if that's what you want: for (int j = 1; j <= 3; j++). Commented Oct 26, 2013 at 23:54
  • I get an ArrayOutofBounds = -1 when I do this though. It looks like the error is on the second to last line. Commented Oct 26, 2013 at 23:59

1 Answer 1

1

There are 21 elements in your array. From the description you mentioned, you want to seperate it into 3 parts. Each part has 7 elements and reverse them.

For the each part, we can do the swap data opearation.

  1. Swap the 1st element with the 7th element.
  2. Sawp the 2nd element with the 6th elememt.
  3. Swap the 3rd element with the 5th element. ... ...

Note: The end condition is 7/2 for data swap. It is the middle index of the 7 elements.

Here one more thing is to determine what is the start index and end index for each divided part.

Thefollowing code is working for your requirement. Hope this can help you some.

    for (int j = 0; j <3; j++) {
        for (int k = 0; k <7/2; k++) {
            int newj = j+1;
            int array = integer[7*newj-k-1];
            integer[7*newj-k-1]= integer [7*j+k];
            integer [7*j+k] = array;
        }
    }
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.