How to count the number of times a number or more repeats within a vector in c?

Asked

Viewed 3,414 times

4

I need to do this exercise and I’m locking in on the countdown. Make a program that reads an 8-position vector and checks for equal values and write them (each repeated number should only appear once in the answer)

Output example:

<< Valores iguais >>
Entre com o número 1: 5
Entre com o número 2: 6
Entre com o número 3: 4
Entre com o número 4: 5
Entre com o número 5: -3
Entre com o número 6: -3
Entre com o número 7: -3
Entre com o número 8: 6
Valores repetidos: 5, 6, -3

My code so far:

int main(){
    int vetor[8];
    int i,x,j,k;
    int newVetor[8];

    int n=0;    

    printf("<< Valores iguais >>\n");

    for(i=0; i<8; i++){
        printf("Entre com o numero %i: ",i+1);
        scanf("%i",&vetor[i]);
    }

    for(i=0; i<8;i++){
        for(x=i+1;x<8;x++){
            if(vetor[i] == vetor[x]){
                newVetor[n] = vetor[i]; 
                n++;    
            }
            else{}
        }
    }
}
  • A possible solution is, after reading the elements of the vector, to order it and then to verify eventual duplicities.

2 answers

0

A hint, use the size of the vector in a variable or calculate it! Avoid using "hard coded" numbers, so if you change the size of it, you have to change in several places, making it difficult to change/maintain your code.

Follow the example according to what you want:

#include <stdio.h>

#define LENGTH 8     

int main() {
    
    int vetor[LENGTH];     
        
    for(int i=0; i < LENGTH; i++){
        printf("Entre com o numero %i: ",i+1);
        scanf("%i",&vetor[i]);
    }    
        
    printf("Valores repetidos: ");    
    // Procura os repetidos   
    for(int j = 0; j < LENGTH ; j++) {    
        for(int k = j + 1; k < LENGTH; k++) {    
            if(vetor[j] == vetor[k])    
                printf("%d, ", vetor[k]);    
        }    
    }   
    return 0;
}
  • In that case a #define length 8 would not be better?

  • Yes, it would be. Thank you, I will edit.

0

I highlight the following excerpt from your code:

for(i=0; i<8;i++){
        for(x=i+1;x<8;x++){
           printf("%d\t%d\t%d\n", vetor[i], vetor[x], n);
            if(vetor[i] == vetor[x]){
                newVetor[n] = vetor[i];
                n++;
            }
            else{}
        }
    }

It even works well if the user type a number at most twice, but if the user, for example, type the same number in the eight entries, the condition vetor[i] == vetor[x] will always be true and variable n would achieve, in theory, the value 28. I say in theory, because when n reaches 8, the instruction newVetor[n] = vetor[i] starts writing outside the limits of the newVetor array, so the behavior of the code cannot be defined beforehand.

Using brute force, you could solve the problem like this:

   int a = 0;
   int flag = 1;
    for(i=0; i<8;i++){
        for(x=i+1;x<8;x++){

            if(vetor[i] == vetor[x]){
                  //verifica se vetor[i] já foi incluído em newVetor
                  // e armazena o resultado na variável flag
                  // flag == 0 (já foi incluído) flag == 1 (ainda não foi incluído)
                  for(a = 0; a < n; a++){
                     if(vetor[i] == newVetor[a]){
                         flag = 0;
                     }
                  }
                  //se ainda não foi incluído, inclua o valor de vetor[i] em newVector
                  if(flag) {
                      newVetor[n] = vetor[i];
                  n++;
               }
            }
            //reseta o valor de flag para as próximas repetições
            flag = 1;
        }
    }

   printf("Valores repetidos: ");
   for(i = 0; i<n; i++){
      printf("%d ", newVetor[i]);
   }

  • I’ll test it here

Browser other questions tagged

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