fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. #define MAXVAL 50
  5.  
  6. unsigned int CountDistinctsElements(unsigned int* iArray, unsigned int iNbElem) {
  7. unsigned int ret = 0;
  8.  
  9. //this array will contains the count of each value
  10. //for example, c[3] will contain the count of the value 3 in your original array
  11. unsigned int c[MAXVAL];
  12. memset(c, 0, MAXVAL*sizeof(unsigned int));
  13.  
  14. for (unsigned int i=0; i<iNbElem; i++) {
  15. unsigned int elem = iArray[i];
  16. if (elem < MAXVAL && c[elem] == 0) {
  17. ret++;
  18. }
  19. c[elem]++;
  20. }
  21. return ret;
  22. }
  23.  
  24. int main() {
  25. unsigned int myElements[10] = {0, 25, 42, 42, 1, 2, 42, 0, 24, 24};
  26. printf("Distincts elements : %d\n", CountDistinctsElements(myElements, 10));
  27. return 0;
  28. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Distincts elements : 6