Reputation: 8933
I have an array of 6 elements A[0,1,2,3,4,5] and I have another of 3 elements B[2,1,3].
I want to split array A into 3 chunks based on the values in array B, as follows: Array[0,1] Array[2] Array[3,4,5]
I then want to create a third array that that takes element 0 of each new array and create a new array, as follows:
new array[0,2,3]
Can any one give me an idea how to do this?
Upvotes: 0
Views: 639
Reputation: 283
If you're only interested in the final result, you would not need to create the intermediate arrays and simply use indexes and a loop over the arrays:
int[] a = new int[] { 0, 1, 2, 3, 4, 5 };
int[] b = new int[] { 2, 1, 3 };
int indexA = 0;
int indexB = 0;
int[] result = new int[b.length];
while (indexA < a.length && indexB < b.length) {
result[indexB] = a[indexA];
indexA += b[indexB];
indexB++;
}
for (int r : result) {
System.out.println(r);
}
Upvotes: 0
Reputation: 8386
Here you go, this time. But next time, as Rohit Jain said, do some research, try on your on. You don't learn how to program or think logical by delegating your tasks to others.
The function
public int[] foo(final int[] values, final int[] sizes) {
final int[] results = new int[sizes.length];
int index = 0;
for (int i = 0; i < sizes.length; i++) {
if (index > values.length)
break;
results[i] = values[index];
index += sizes[i];
}
return results;
}
And example call:
final int[] values = new int[] {0, 1, 2, 3, 4, 5,};
final int[] sizes = new int[] {2, 1, 3};
final int[] fooedArray = foo(values, sizes);
Upvotes: 1