Created
March 12, 2020 19:43
-
-
Save slwu89/5fe91976df4c5995c818e7729da521c8 to your computer and use it in GitHub Desktop.
how to get unique elements and how many times they appear in an array of ints (for C, but compiled with C++)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example program | |
#include <iostream> | |
#include <string> | |
int main(void) { | |
int arr[13] = {1, 2, 2, 123121, 123121, 3, 5, 6 , 7, 7, 14, 2, 16}; | |
int len = 13; | |
int unique[len]; | |
int duplicates[len]; | |
int j, n, count, flag; | |
unique[0] = arr[0]; | |
count = 1;/*one element is counted*/ | |
for(j=0; j <= len-1; ++j) { | |
duplicates[j] = 1; | |
flag = 1;; | |
/*the unique array will always have 'count' elements*/ | |
for(n=0; n < count; ++n) { | |
if(arr[j] == unique[n]) { | |
if(j != n){ | |
duplicates[n] += 1; | |
} | |
flag = 0; | |
} | |
} | |
if(flag == 1) { | |
++count; | |
unique[count-1] = arr[j]; | |
} | |
} | |
printf("count: %d \n", count); | |
for(int k=0;k<count;k++){ | |
std::cout << "unique elem: " << unique[k] << " appearing " << duplicates[k] << " times" <<"\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment