If I understand you, you want the number of numbers that are repeated in the vector. Example: {1, 2, 3, 3, 3} must return that 1 number repeats (the 3). The vector {1, 3, 3, 2, 1, 4, 4, 5} should return four, since four values are repeated in vector (1, 2, 3 and 4).
In your case, it was not clear if the vector is ordered. So I implemented quick sort to do this, which makes solving the problem a lot easier.
Furthermore, it was not clear whether the original vector could be modified. For this reason, I created a copy of it ( v2
) and ordered it. The repeticoesNumero
variable is getting the number of times a value appears in the vector. If this value is greater than one, it means that the value repeats, and thus increments the variable resposta
, which at the end of execution will have the number of elements that are repeated in the vector. Below the code:
#include <stdio.h>
#include <stdlib.h>
void quickSort(int a[], int l, int r) {
int j;
if(l < r) {
j = partition( a, l, r);
quickSort(a, l, j-1);
quickSort(a, j+1, r);
}
}
int partition(int a[], int l, int r) {
int pivot, i, j, t;
pivot = a[l];
i = l;
j = r+1;
while(1) {
do
++i;
while(a[i] <= pivot && i <= r);
do
--j;
while(a[j] > pivot);
if( i >= j ) break;
t = a[i];
a[i] = a[j];
a[j] = t;
}
t = a[l];
a[l] = a[j];
a[j] = t;
return j;
}
int main() {
int n, i, temp, repeticoesNumero, resposta = 0;
int *v1, *v2;
printf ("Entre com n: ");
scanf ("%d", &n);
v1 = (int *)malloc(n * sizeof (int));
v2 = (int *)malloc(n * sizeof (int));
for(i = 0; i < n; ++i) {
scanf("%d", &v1[i]);
v2[i] = v1[i];
}
quickSort(v2, 0, n - 1);
temp = v2[0];
repeticoesNumero = 1;
for (i = 1; i < n; i++) {
if (v2[i] == temp) repeticoesNumero++;
else {
if (repeticoesNumero > 1) resposta++;
temp = v2[i];
repeticoesNumero = 1;
}
}
if (repeticoesNumero > 1) resposta++;
printf("%i numero(s) se repete(m) no vetor.\n", resposta);
}
Hope this is it!
Just a note : In your code there is a M
in the for
loop. I believe it was just a typo and the original value is N
. My implementation is considering it to be a typo.