Tell me how to use a loop (or loop) to copy elements from one array into two. Consistently - when the first one is filled, put the remaining elements in the second one.
2 answers
Copy from array A to B and C. Pass the first loop
for (var i =0; i < B.length; i++) { B[i]=A[i] }
Then from
for(var j = B.length, j < A.length, k++) { C[j] = A[j] }
- And if pokucheryay (not checking the problem of lack of length of the second array): int [] A1, A2, B, ar; ............. ar = A1; for (int i = 0, j = 0; i <B.length;) {if (j> = ar.length) {j = 0; ar = A2; } ar [j ++] = B [i ++]; } - alexlz
|
If we assume that A.leght >= B.lenght + C.lenght
, then
System.arraycopy(A, 0, B, 0, B.length()); System.arraycopy(A, B.length(), C, 0, C.lenght());
if not, you need to suffer a little.
if (A.length() < B.length()) System.arraycopy(A, 0, B, 0, A.length); // A.lenght < B.length. C - не при делах. else { System.arraycopy(A, 0, B, 0, B.length()); int size = Math.min(C.length(), A.length()-B.length(); System.arraycopy(A, B.length(), C, 0, size); }
And copying through a cycle is sad. In some cases, the performance drop is 5-10 times.
- oneI'm afraid this is a learning task. Cruel and merciless For the answer, of course +, also remembered this method, but did not write - rasmisha
- it is educational, through arraycopy it is impossible)) - tarasman4ik1985
- even if it's a learning task, you need to use arraycopy. But if the teacher does not understand humor, then you can add the implementation separately void arraycopy (Object source, int spos, Object dest, int dpos, int size) {for (int i = 0; i <size; i ++) dest [dpos + i] = source [spos + i]; } (well, remove
System.
in the codeSystem.
) Using a separate method is a beautiful and correct move. - KoVadim - > through arraycopy it is impossible)) because he called cruel and merciless. Teaching classes is also usually based on hellish and unrealistic examples, unfortunately - rasmisha
|