How can I find how many elements are missing from an array of integers in C, if some of the numbers are duplicated?
Assume the array is int array = {1, 2, 1, 5, 4}
and there should be numbers up to 6
. Then, the program/function should output/return 2
, as there are 2 elements missing (3, 6
).
Note: 0 is not counted as a missing number, nor can it be present in an array.
asked Nov 1, 2015 at 1:13
1 Answer 1
This way?
int countMissing(int *x, int arrLen, int bound)
{
int * y = malloc ((bound + 1) * sizeof(int));
int i = 0;
int missing = 0;
memset(y,0,sizeof(int)*(bound+1));
for(i = 0; i<arrLen; i++)
{
if(x[i]<=bound)
{
y[x[i]] = 1;
}else
{
// error handling e.g.
return -1;
}
}
for(i = 1; i<=bound; i++)
{
if(y[i]==0) missing++;
}
free(y);
return missing;
}
Usage:
int main(void)
{
int array [] = {1, 2, 1, 5, 4};
printf("%d", countMissing(array, 5, 10));
return 0;
}
Output: 6.
answered Nov 1, 2015 at 1:23
-
Nits: (1) you should allocate
char *y
to save some space; (2) you should usey[x[i]-1]
or allocate an array of sizebound+1
, because otherwise you have an out-of-bounds access; (3) you should free your array.nneonneo– nneonneo11/01/2015 01:29:33Commented Nov 1, 2015 at 1:29 -
@nneonneo: fixing, I don't have a debugger with me; should work nowgmoniava– gmoniava11/01/2015 01:36:38Commented Nov 1, 2015 at 1:36
-
1Why are you using
memset()
instead ofcalloc()
?Mitsos101– Mitsos10111/01/2015 01:43:23Commented Nov 1, 2015 at 1:43 -
@Mitsos101: That is a style thinggmoniava– gmoniava11/01/2015 01:44:03Commented Nov 1, 2015 at 1:44
-
@Giorgi Does the memory need to be zeroed out anyway though?Mitsos101– Mitsos10111/01/2015 01:48:46Commented Nov 1, 2015 at 1:48
lang-c
n
can have numbers between1
ton+1
?