Count the number of duplicate elements in an array-C
Jun 26, 2017 at 9:00am UTC
Accept an Array of size N and print the total number of duplicate elements (The elements which occur two or more times).
Input Format: The first line contains N. The second line contains the N positive integer values, each separated by a space.
Output Format: The first line contains the count of duplicate elements.
The program I wrote works for only two same elements and fails to read more than 2 duplicates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include<stdio.h>
#include <stdlib.h>
int main()
{
int arr[1000],i,j,n,count=0;
scanf("%d" ,&n);
for (i=0;i<n;i++)
{
scanf("%d" ,&arr[i]);
}
for (i=0;i<n;i++)
{
for (j=i+1;j<n;j++)
{
if (arr[i]==arr[j])
{
count=count+1;
break ;
}
}
}
printf("%d" ,count);
}
Input: n=8
1 2 3 1 2 1 5 6
Here the program returns 3 instead of 2 because of 3 duplicates(1 1 1).
Suggest some ideas to avoid this...
Jun 26, 2017 at 9:57am UTC
1 2 3 4 5 6 7 8 9 10 11 12
#include <unordered_map>
auto countDuplicutes(int arr[1000])
{
std::unordered_map<int , int > retv;
for (int i = 0; i < 1000; ++i)
++retv[iarr[i]];
return retv;
}
countDuplicutes returns key/value map where key = number and value = number of times number appears in array
Last edited on Jun 26, 2017 at 9:57am UTC
Jun 26, 2017 at 10:49am UTC
Figured it out :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include<stdio.h>
#include <stdlib.h>
int main()
{
int arr[1000],temp,i,j,n,count=0;
scanf("%d" ,&n);
for (i=0;i<n;i++)
{
scanf("%d" ,&arr[i]);
}
for (i=0;i<n;++i)
{
for (j=i+1;j<n;++j)
{
if (arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
for (i=0;i<n;i++)
{
for (j=i+1;j<n;j++)
{
if (arr[i]==arr[j])
continue ;
else if (i!=j-1)
count++;
i=j;
}
}
printf("%d" ,count);
return 0;
}
Topic archived. No new replies allowed.