Reputation: 9
New to programming, so please bear with me! In C, say you have an array {0, 1, 0, 1, 0, 0, 0}. How do I return the index position of ALL the values that are 1? So in this case it would be {1, 3}. I have no trouble when I am looking for the max/min/occurrences in an array, because you can just keep an ongoing 'count' of values. However I can't get my head around this one as I don't see how the for loop works here. Here's what I've tried:
for (i = 0; i < numValues; i++) {
if (array[i] == 1) {
result[i] = i;
} }
Where result[] is a new array (I think I need a new array since there is more than 1 output). But this only finds the first occurrence and forgets about the second.
Thanks for the help!
Upvotes: 1
Views: 758
Reputation: 1601
As you are newer to Programming, lets make it simple.
Lets assume you are not worried about the space/memory that result
holds.
int onesCount = 0; // number of 1(s) count
for (i = 0; i < numValues; i++) {
if (array[i] == 1) {
result[onesCount] = i;
onesCount++;
}
}
Upvotes: 1
Reputation: 96937
Keep a separate index for occurrences. If result
needs to only hold the number of occurrences, you'll need to keep two arrays (one temporary, one for the final result) or do a first pass through array
to find out how many occurrences or matches exist, before making a second pass to copy over indices. Here's how to do it with two arrays:
int occurence = 0;
int* occurrences = malloc(sizeof(int) * numValues);
for (int i = 0; i < numValues; i++) {
if (array[i] == 1) {
occurrences[occurence++] = i;
}
}
int* result = malloc(sizeof(int) * occurence);
for (int i = 0; i < occurence; i++) {
result[i] = occurrences[i];
}
free(occurrences);
/* do stuff with result... */
free(result);
You could do it in one pass by resizing the result
array on each match via realloc
, but that would take more time.
Upvotes: 2