Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding number of repeated elements in an array using C

Tags:

arrays

c

I am unable to find the correct logic to find the number of repeated elements in an array. I can understand why my logic is not working, but I am not able to overcome it.

Following is the actual question:

Write a program that declares an integer array arr of size n. It first takes in a positive integer n from the user. Then reads n numbers and stores them in arr. It checks and prints the number of repetitions in arr. The result is the sum of the total number of repetitions in the array.
Example: If arr = [4,3,4,4,3,4,5]
Then number of repetitions is 6 (which is 4 repetitions of 4 + 2 repetitions of 3)

Following is my code:

#include <stdio.h>

int main() {
    int n, i, j, count = 1, p = 0;
    printf("Enter the length of array");
    scanf("%d", &n);
    int arr[n];
    for (i = 0; i < n; i++) {
        printf("Enter a number\n");
        scanf("%d", &arr[i]);
    }
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                count++;
                break;
            }
        }
        if (count != 1) {
            p = p + count;
            count = 1;
        }     
    }
    printf("Number of repetitions are %d", p);
}

For the above code if we take the array as mentioned in the question, then each time my code encounters two same 4's, it counts both of them, hence my program ends up counting extra number of 4's. So I am unable to find some better logic to over come it.
(I am a beginner so I doesn't no much advanced function/methods used in C)

like image 298
sameed hussain Avatar asked Mar 02 '23 08:03

sameed hussain


1 Answers

One of the things that you can do is, keep an extra array for the numbers you have checked and each time when you compare numbers you would check if you have already seen this number or not.

I also want to include a few another approach to this problem. If we know that numbers in the list won't be so big we can use an array to keep track of counts.

//numbers = {4, 3, 4, 4, 3, 4, 5}
int max = findMaxValue(numbers);
int counts[max]; //should be done with dynamic memory allocation
for(i=0;i<max;i++){
    counts[max] = 0;
}
for(i=0;i<numbers.size;i++){
    counts[numbers[i]]++;
}
int sum = 0;
for(i=0;i<max;i++){
    if(counts[i] > 1){
        sum += counts[i];
    }
}

Another thing that you can do is, sort the numbers first and then compare adjacent elements.

like image 70
Metin Usta Avatar answered Mar 10 '23 09:03

Metin Usta