How to check and print values that are repeated in a vector

0

I have the following problem to check the vectors that are repeated in a Vector:

Given a sequence of n real numbers, determine the numbers that make up the sequence and the number of times each occur in it.

Example:

n = 8

Sequence:

-1.7, 3.0, 0.0, 1.5, 0.0, -1.7, 2.3, -1.7

Output:

-1.7 occurs 3 times

3.0 occurs 1 time

0.0 occurs 2 times

1.5 occurs 1 time

2.3 occurs 1 time

Here is the code I wrote here in C ++:

#include <iostream>
using namespace std;
int main () {
	int n, i, i2, i3, a, cont=0;
	cin>>n;
	float vet[n], vet2[n], vet3[n];
	for(i=0 ; i<n ; i++){
		cin>>vet[i];
		vet2[i]=vet[i];
	}
	for(i=0 ; i<n ; i++){
		cont=0;
		for(i2=0 ; i2<n ; i2++){
			if(vet[i]==vet2[i2]){
				cont++;
				vet3[i]=vet[i];
			}
		}
		cout.precision(1);
		cout<<fixed<<vet[i]<<" ocorre "<<cont<<" vezes"<<endl;		
	}
			
	
	return 0;
}	

At the moment I'm having the following result:

The problem is that the repeated values are being shown in the amount of times it contains within the vector, not just one as it asks for the exercise.

: /

    
asked by anonymous 18.08.2017 / 17:25

2 answers

0

Colleague, I have not programmed C for some time, but I did what you need in javascript, the logic is the same

var array = [1,2,3,2,4,5,6,3,6,8,7,4]
var arrayVerificado = [];

for(var i = 0; i < array.length; i++){
	var contador = 0;  
  var repetiu = false;
  
  for(var z = 0; z < arrayVerificado.length; z++){
  	if(arrayVerificado[z] == array[i]){
     //Verifico se no array auxiliar, o número já foi verificado, caso sim, seto a variavel repetiu para true.
    	repetiu = true
    }
  }  
  if(repetiu == false){ //caso não tenha repetido, eu deixo o padrão false.
  arrayVerificado.push(array[i])//add no meu array auxiliar que este número vai ser verificado
    for(var j = 0; j < array.length; j++){
      if(array[i] == array[j]){ //se ele achar, faço meu contador acrescentar +1
        contador++
      }
      
    }
      console.log("O número: "+ array[i]+ " repetiu: "+ contador + " vezes");
      }

}
    
18.08.2017 / 19:32
0

The problem is that you are assigning a value of 8 to N, say your vector:

vet[0] = -1.7
vet[1] = 3
vet[2] = 0
vet[3] = 1.5
vet[4] = 0
vet[5] = -1.7
vet[6] = 2.3
vet[7] = -1.7

Then every time it will check, because in its for it will go through this vector 8 times, for example in your case in position 0 5 and 7 of your vector, we have the value -1.7, so when it falls in the second% with% will do this check in positions 0, 5 and 7. Also note that your command to print for is just after the second repeat command ends and before the first one will start again, then it will print all 8 times.

    
18.08.2017 / 19:00