How can you count repeated numbers in a vector?

Asked

Viewed 14,069 times

0

I’m wondering if there are how many repeated values in the vector.

Here’s the code I tried, but I didn’t 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;
}
  • 1

    I recommend using more descriptive names in your variables. i and j until they are self-explanatory due to conventions, but a could be called quantidadeDeEntradas and c could be called repeticoesEncontradas, for example. It’s easier for those reading your code to be able to help you. Also, explain your problem better. Give examples of matching expected inputs and outputs.

1 answer

2


The way 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 position of the vector with itself will always result in equal elements being compared. This case is not interesting and should not be told.

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

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

The solution to both problems is simply to exchange the j = 0 of for internal 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.