Reputation: 4807
I have an array with zero values, and I wish to copy this array to other array but without the zero values. How can I do this if determining the array size is not possible because I do not know how many zeros are there. Please note that I can not use List or ArrayList because of reasons.
// frame is the original array
final int[] sorted = new int[??];
for (int i = 0; i < frame.length; i++) {
if (frame[i] != 0) {
sorted[i] = frame[i];
}
}
Upvotes: 0
Views: 1292
Reputation: 28823
Yo can do this if it must use array:
int j = 0;
for (int i = 0; i < frame.length; i++) {
if (frame[i]!=0) {
j++
}
}
final int[] sorted = new int[j];
j = 0;
for (int i = 0; i < frame.length; i++) {
if (frame[i]!=0) {
sorted[j] = frame[i];
j++;
}
}
Upvotes: 1
Reputation: 1249
Try the following:
String validNumbers = "";
for (int i = 0; i < frames.length; i++) {
if (frames[i] != 0)
validNumbers += (i > 0 ? ";": "")+frames[i];
}
String sorted[] = validNumbers.split(";");
This way, You'll have an array of String
with the numbers that are different of 0;
Upvotes: 1
Reputation: 1626
int noneZeroCount= 0;
for (int i = 0; i < frame.length; i++) {
if (frame[i]!=0) {
noneZeroCount++;
}
}
final int[] sorted = new int[noneZeroCount];
// You got size of non zero elements in array now run copy loop
Upvotes: 0
Reputation: 7065
The only way I know how to do this with your given constraints would be to COUNT FIRST, Process NEXT:
unsigned int nonZeroCount = 0;
// Count the amount of non-zero values
for (int i = 0; i < frame.length; i++){
if (frame[i]!=0)
nonZeroCount++;
}
// Create the NEW Array
final int[] sorted = new int[nonZeroCount];
// NEXT add them to your new array, Need to have 2 separate counters, 1 for your initial array,
// Another for where you are placing it within your new array
unsigned int anotherCount = 0;
for (int i = 0; i < frame.length; i++){
if (frame[i]!=0){
sorted[anotherCount ] = frame[i];
anotherCount++;
}
}
Upvotes: 1
Reputation: 2371
You could make a new array with the same size like the one you test. After that you iterate over the array and for each non zero value you found, you add it, while increasing a counter that will represent the number of non zero elements found. After this you can use it to create a new array where to copy your values or simple use the counter as a upper bound when iterating the new array.
Upvotes: 0
Reputation: 1249
I do not know much zeros there is.
So why don't you fond out?
int counter = 0;
for (int i = 0; i < frame.length; i++) {
if (frame[i]==0){
counter++;
}
}
Upvotes: 0