algorithm - Array - Eliminate all duplicates C++ -
i have next array
a[0]=4, a[1]=6, a[2]=9, a[3]=4, a[4]=4 ...
i want eliminate duplicate values array , print array. array 4 6 9 4 4
become 4 6 9
i've written code this:
for(int i=0;i<=n-1;i++) { if(frec[a[i]]>1) //see if there duplicate values in frequency array. { for(int j=i;j<=n-1;j++) a[i]=a[i+1]; frec[a[i]]--; n=n-1; } }
however instead of 4 6 9
6 6 9
. give thanks you.
edit: total code
#include <iostream> #include <limits.h> using namespace std; void readarray(int a[], int frec[],const int &n) { for(int i=0;i<=n-1;i++) { cout<<"a["<<i<<"]="; cin>>a[i]; frec[a[i]] += 1; } } void printarray(int a[], int frec[], const int &n) { for(int i=0;i<=n-1;i++) cout<<a[i]<<" "; cout<<endl; for(int i=0;i<uchar_max;i++) cout<<frec[i]<<" "; cout<<endl; } void eliminareduplicate(int a[],int frec[], int &n) { for(int i=0;i<=n-1;i++) { if(frec[a[i]]>1) { for(int j=i;j<=n-1;j++) a[i]=a[i+1]; frec[a[i]]--; n=n-1; } } } int main() { int a[100], frec[uchar_max]={0}, n; cout<<"n= "; cin>>n; readarray(a,frec,n); eliminareduplicate(a,frec,n); printarray(a,frec,n); }
one thing sure worst programme design detect/remove duplicates in array. that's because size of frec array depends on numbers in array.
so, improve alternative go std::set
or
if don't want ordering among elements can take hash-table implementation this.
c++ algorithm duplicates
No comments:
Post a Comment