Sunday, August 2, 2009

Program in c++ to remove duplicates from an array. e.g.if 2 occurs more then once , it should occur only once.

One way to do this, not taking advantage of what C++ gives you, is to simply use an array, e.g. int a[N], sort it, then search for adjacent values that are equal, and remove the duplicates. This is a fairly crude approach, and involves a lot of copying to compress the array when you remove an element. For example:


if a[i] == a[i+1], for j = i+2 to N-1, set a[i+1] = a[j]


When you're done packing the array, adjust the length to account for the deleted values. Of course, if a value is duplicated more than once, with a little extra logic you can delete all the duplicates in one shot, saving some iterations in your loop.





Sorting can be a pain, and using a plain old data array is primitive when you can use C++'s vector%26lt; %26gt; instead. In the example below, I keep the list sorted as it's created, saving the trouble of sorting it later. The way I did that isn't particularly clever, so maybe you can think of a more efficient solution there. After the "array" has been filled, I let vector do the tedious maintenance as I remove duplicate elements. If efficiency isn't your main concern, using vector%26lt; %26gt; is the way to go. If you need to optimize, you may use a plain old data array and do the work yourself. But there's no guarantee your solution would be more efficient than what vector%26lt; %26gt; does for you.





#include %26lt;iostream%26gt;


#include %26lt;vector%26gt;


#include %26lt;cstdio%26gt;





using namespace std;





int main(int argc, char *argv[]) {


vector%26lt;int%26gt; intVec;


bool done = false;


int x;





cout %26lt;%26lt; "Enter integers for array, 'x' to end :" %26lt;%26lt; endl;


while (!done) {


if (scanf("%d",%26amp;x) == 1) {


// Insert, keeping vector sorted


vector%26lt;int%26gt;::iterator loc = intVec.begin();


while ((loc != intVec.end()) %26amp;%26amp; (*loc %26lt; x)) ++loc;


intVec.insert(loc,x);


} else {


done = true;


}


}





// Remove duplicates


vector%26lt;int%26gt;::iterator iter = intVec.begin();


while (iter != intVec.end()) {


while ((iter+1 != intVec.end()) %26amp;%26amp;


(*iter == *(iter+1))) {


intVec.erase(iter+1);


}


++iter;


}





// Print array


for (vector%26lt;int%26gt;::iterator iter = intVec.begin();


iter != intVec.end(); ++iter) {


cout %26lt;%26lt; *iter %26lt;%26lt; endl;


}


return 0;


}

columbine

No comments:

Post a Comment