Finding amount of elements that have one or more copies in an array

Hello, well it sounds more like an algorythmic problem, but maybe there is a built-in function already or something similar, if not I'd appreciate any help ;).
Basically the problem sounds simple, we have an array of X elements and we have to find out how many elements in that array occur more than one time, in example :
1
2
3
4
5
6
7
8
9
10
11
12
a
a
b
c
d
e
f
e
c
g
h
j


The elements that occur one than more time are : a+c+e - therefore
the outcome =3.

I tried something like this :
1
2
3
4
5
6
7
8
9
10
int h=0;
int elementcount=0;
vector<string> vs; // lets say it already contains x amount of strings in //seperated lines
for(int i = 0; i < vs.size(); i++){
   for(int j = 0; j < vs.size(); j++){
         if(vs[i]==vs[j] && i!=j){
             h++;
         }    
      }if(h>0){elementcount++; h=0;}
   }


The problem with this solution is simple - it counts all the elements instead of just one case of a specific argument, for example :
a+a+c+c+e+e - > the outcome = 6.

I thought about making another container for the elements that already occured earlier on which would automatically exclude them from incrementing elementcount, but hell... that sounds a bit "too" complicated for such a "simple" problem, do you guys have any advices / thoughts of better solutions ?
Just make j (the second looping variable) relative to i (the first looping variable), like so:
1
2
3
4
5
6
7
for (int i = 0; i < vs.size() - 1; i++)
{
    for (int j=i+1; i < vs.size(); i++ )
    {

    }
}

then once an element has been compared with all others, i.e. when i has done one complete loop, it won't be included in the following comparisons
Last edited on
Aye, I thought about this before, but there comes another problem with such solution, what if there are more copies of the element that already occured, ie.
vs=1,2,1,2,1,2;
I will try to show how this works right now :
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
vs=1,2,1,2,1,2;
vs[i]==vs[j];
i = 0, j = i+1(1).
1==2 
j++;
1==1;
h++;
j++;
1==2;
j++;
1==1;
h++;
j++;
....
elementcount++; (because h > 0) h = 0;
i = 1; j = i+1(2);
2==1;
j++;
2==2;
h++;
j++;
...
elementcount++; (cus h> 0) h = 0;
i = 2; j = i + 1 (3);
1==2;
j++;
1==1;
h++;
j++;
...
elementcount++; (WRONG, elementcount is already equal to 3, while 2 is the correct answer) h = 0;
...


Thing is if an element that already had met its equivalent has more copies of them futher on in the array, the copies will be checked with other copies and in effect they will be counted as well.
Last edited on
Topic archived. No new replies allowed.