views:

149

answers:

4

Hey guys,

I've got an array array of size N. For every 3 indexes in it I want to take them out and declare and assign those values to another array of size 3. I then want to go back to that array and take the next 3 and put it in a different array of size 3. I'll iterate like this for 3 different arrays of size 3 a1,a2,a3 once this is done I want to empty a1,a2,a3 and re add the NEXT 3 values to the 3 arrays of size 3 repeating this on till we reach array.length

What would be the best / most efficient way of doing this?

A: 

for(int i = 0; i < ##; i++){if(i%3==0){startNewArray}}

foret
+7  A: 

As a general strategy I would not worry about efficiency at first.

Code it as explicitly as possible, and then write a load of unit tests confirming it works. The iteratively improve performance.

Its easier to make correct code fast than it is to make fast code correct.

Visage
+1 For "Its easier to make correct code fast than it is to make fast code correct."
Jason Day
+1 love that quote!
Bob Fincheimer
+3  A: 
for (int i=0; i<=N-9; i+=9) {
 System.arrayCopy(arrayN, i, a1, 0, 3);
 System.arrayCopy(arrayN, i+3, a2, 0, 3);
 System.arrayCopy(arrayN, i+6, a3, 0, 3);
 // presumably do other stuff here
}

That's a pretty brittle but fast way of doing it. Each time the previous values are overwritten, so no need to clear. If you do need to have arrayN clear, you can just Arrays.fill(arrayN, null) after the loop.

EDIT: For the less brittle answer, I'm going to assume you'd be inflating m x n arrays. Instead of hard coding a1, a2, ... am, make a 2D array a[m][n].

for (i=0; i<=N-m*n; i+=m*n) {
 for (int j=0; j<m; j++) System.arrayCopy(arrayN, i+n*j, a[j], 0, n);
 // presumably do other stuff here
}

and, as Adrian suggests in the comments, declare i outside the loop and use its value relative to N to deal with leftovers as appropriate.

Carl
+1 it was what I had in mind when I commented on the question.
Adrian Regan
@Adrian: this should satisfy the wrong length problem, provided the correct response is to not barf and work with as much of the array as possible. Alternately, if somehow N is known to be a multiple of 9, the loop control could be modified to just `i<N`.
Carl
@Carl You could declare 'i' outside the loop and perform a post loop scoop up of the remaining items if it is not a multiple of 9
Adrian Regan
A: 

Its very easy, you can do it in the following way.... It is code snippet below....

byte[] YourBigArray = new byte[SomeValue];

int temp = 0;

while(temp < YourBigArray.size - 1 ) { System.arrayCopy(YourBigArray, temp, smallarray, 0, 3); temp+=3; }

Try this code and also see the documentation of arrayCopy function....

Enjoy.....

Darshan G. Prajapati