Search for pairs in an array

So what I'm trying to do is code to find a pair of numbers in an array. This code below works fine when there is one pair of numbers.

#include<stdio.h>
main()
{
    int arr[10], i, j, pairs = 0;
    int n;
    scanf("%d", &n);
    for(i = 0; i<n; i++)
    {
        scanf("%d", &arr[i]);
    }
    for(i = 0; i<n; i++)
    {
        for(j = i+1; j<n; j++)
        {
            if(arr[i] == arr[j])
            {
                pairs++;
            }
        }
    }
    printf("%d", pairs);

}

I want to make it work when there are three identical elements. For example, arr [5] = 1, 1, 1, 2, 2, it should return 2 pairs (1.1 and 2.2 with an extra 1 left), but it returns 4 pairs instead of my code!

Thank.

+6
source share
3 answers

Here you compare each element one by one with every other element, why you get the answer as 4.

To count pairs for three or more three, one approach would be to sort the array, and then count the number of times this element occurred, and if the frequency is greater than 2, which means that it forms a pair. Here is the modified code:

#include<stdio.h>
main()
{
    int arr[10], i, j, pairs = 0,count=0,prev_element=0;
    int n;
    scanf("%d", &n);
    for(i = 0; i<n; i++)
    {
        scanf("%d", &arr[i]);
    }

    // You need to sort the array here.

    prev_element = arr[0];
    count=1;
    for(i = 1; i<n; i++)
    {
        if(prev_element==arr[i])
        {
            count++;
        }
        else
        {
            if(count>=2)
                pairs+=count/2;
            else
            {
                prev_element=arr[i];
                count=1;
            }
        }
    }
    printf("%d", pairs);
}

. O (n2), O (n).

, -, , , , , .

+1

, . .

. .

#include<stdio.h>
main()
{
    int arr[10], check[10], i, j, pairs = 0;
    int n;
    scanf("%d", &n);
    for(i = 0; i<n; i++)
    {
        scanf("%d", &arr[i]);
        check[i]    =   0;
    }
    for(i = 0; i<n; i++)
    {
        for(j = i+1; j<n; j++)
        {
            if(arr[i] == arr[j] && check[j] ==  0   &&  check[i]    ==  0)
            {
                pairs++;
                check[j]    =   1;
                check[i]    =   1;
            }
        }
    }
    printf("%d", pairs);

}
0
#include<stdio.h>
main()
{
    int arr[10], i, j, pairs = 0;
    int n;
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }
    bubbleSort(arr,n);

    for(i = 0; i < n-1; i++)
    {
        if(arr[i] == arr[i+1])
        {
            pairs++;
            /*Skip the paired index*/
            i++;
        }
    }
    printf("%d", pairs);
}
0
source

Source: https://habr.com/ru/post/1686758/


All Articles