-2

How can I convert an Array [1, 2, 3, 4, 5, 6, 7 ,8, 9, 10, 11, 12] to a 2D-Array looking like this?

[[1,  2,  3],
 [4,  5,  6],
 [7,  8,  9],
 [10, 11, 12]]

Always 3 Numbers in a row.

What I have tried returns the first line correct, but the other lines are the same as the first.

for (int i = 0; i < array.length; ++i) {
    for (int k = 0; k < 3; ++k) {
    result[k][i] = args[i];
    }
5
  • Any efforts put in till now? Commented May 21, 2014 at 12:25
  • Hint: use two nested loops. That's not the only solution - read this answer to find out more. Commented May 21, 2014 at 12:26
  • Sry I've edited the question. Commented May 21, 2014 at 12:28
  • Hint 2 : Think what will the values of i and j be on each iteration of the loop. Commented May 21, 2014 at 12:30
  • SO is not a suitable resource for learning programming basics. You would be better talking to your teacher or reading a book. Commented May 22, 2014 at 9:25

3 Answers 3

1

This shall work for you:

for (int i = 0; i < array.length/3; ++i) {
  for (int k = 0; k < 3; ++k) {
    result[i][k] = args[i*3+k];
  }
}

Here we are computing the source index array based on i*3+k to keep on getting the next index value.

Sign up to request clarification or add additional context in comments.

Comments

0

An one-line and debatably readable solution would be:

int[] foo = {1, 2, 3, 4, 5, 6, 7 ,8, 9, 10, 11, 12};
System.out.println(
    Arrays.deepToString(
        new int[][]
            {
                Arrays.copyOfRange(foo, 0, 3),
                Arrays.copyOfRange(foo, 3, 6),
                Arrays.copyOfRange(foo, 6, 9),
                Arrays.copyOfRange(foo, 9, 12)
            }
        )
);

Output

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Note

Method Arrays.copyOfRange is only available from Java 6. Otherwise you have to use System.arrayCopy which returns void (not applicable to example as is).

Comments

0

arr1 - array with input numbers

arr2 - array with output numbers

for(int i=0;i<arr1.length;i++)
for(int j=0;j<3;j++)
arr2[i][j]=arr1[i*3+j];

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.