How to know how to count repeated numbers in a vector?

0

I'm wondering if there are any repeated values in the array.

Here is the code I tried, but I did not succeed.

#include <stdio.h>

int main(int argc, char** argv)
{
  int a, i, j, c = 0;
  scanf("%d", &a);
  int vetor[a];
  for(i = 0; i < a; i++)
  {
     scanf("%d", &vetor[i]);
  }
  for(i = 0; i < a; i++)
  {
     for(j = 0; j < a; j++)
     {
         if(vetor[i] == vetor[j])
         {
            c++;
         }
     }
 }
   printf("%d\n",c);
   return 0;
}
    
asked by anonymous 29.01.2018 / 16:28

1 answer

1

As you put it, there will be a cases where i and j are equal and therefore vetor[i] and vetor[j] are equal, after all comparing a vector position with itself will always result in equal elements being compared. This case is not interesting and should not be counted.

Another thing is that counting i and j , both from 0 to a - 1 , if in position 3 and in position 5 there is a repetition, it will be counted twice, one with i = 3 and j = 5 and another with i = 5 and j = 3 .

So if there are x repetitions, your program is giving 2 * x + a .

The solution to both problems is simply to change the j = 0 of% internal for by j = i + 1 .

See the corrected code:

#include <stdio.h>

int main(int argc, char** argv) {
    int a, i, j, c = 0;
    scanf("%d", &a);
    int vetor[a];
    for (i = 0; i < a; i++) {
        scanf("%d", &vetor[i]);
    }
    for (i = 0; i < a; i++) {
        for (j = i + 1; j < a; j++) {
            if (vetor[i] == vetor[j]) {
                c++;
            }
        }
    }
    printf("%d\n", c);
    return 0;
}

See here working on ideone.

    
29.01.2018 / 16:39