If I understand correctly, you want the number that repeats in the vector. Example: {1, 2, 3, 3, 3} must return that 1 number repeats (the three). The vector {1, 3, 3, 2, 2, 1, 4, 4, 5} must return four, because four values are repeated in the vector (1, 2, 3 and 4).
In your case, it is unclear whether the vector is ordered. So I implemented Quick Sort to do this, which makes solving the problem much easier.
Also, it was unclear if the original vector could be modified. For this reason, I created a copy of it (v2
) and ordered it. The variable repeticoesNumero
is receiving the number of times a value appears in the array. If this value is greater than one, it means that the value repeats, and so increments the variable resposta
, which at the end of the execution will have the number of repeating elements 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);
}
I hope that’s it!
Just one observation: in your code there is a M
in the loop for
. I believe it was just a typo and the original value is N
. My implementation is considering that it was a typo.
What is the criterion for determining whether it is repeated? Any number that appears at least twice is all occurrences are considered repeated?
– Maniero
wanted as output only the amount of numbers that repeat and not how many times repeated. for example, vector: 1, 2 , 3, 3, 2 with output: 2.
– Leko
the output is 2 because repeat occurs with the 3 and c/ the 2?
– Maniero
exactly! I’m sorry if I wasn’t clear
– Leko
I think it’s much more complicated than that, I need to think, but I think only if I use an auxiliary vector.
– Maniero
I’m trying to reduce the problem in parts because I’m struggling to figure out how to solve it. maybe with the statement it’s clearer for you to understand, right?
– Leko
Will need the input data later, or just count the repeated groups and died?
– Maniero