-3
int arr[] = {10, 20, 20, 10, 10, 30, 50, 10, 20};

I want to compare each element in an array so that I can make pairs of similar numbers using C/C++.

In above example there are three pairs (10-10, 20-20, 10-10). I want to find number of pairs in given array(i.e. 3).

Can anyone please help me with logic?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
user13183713
  • 25
  • 1
  • 2

2 Answers2

2

The approach using C can differ from the approach using C++ because for example in C++ you can use standard containers and algorithms while in C they are absent.

So I will show a solution that can be implemented in the both languages.

Here you are. The program is written using C but it is easy can be transformed in a C++ program by substituting the header and only one statement: the output statement.

#include <stdio.h>

int main( void )  
{ 
    int a[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };
    const size_t N = sizeof( a ) / sizeof( *a ); 
    size_t total = 0; 

    for ( size_t i = 1; i < N; i++ ) 
    { 
        size_t count = 1; 
        for ( size_t j = 0; j < i; j++ ) 
        { 
            if ( a[i] == a[j] ) ++count; 
        } 

        if ( count % 2 == 0 ) ++total; 
    } 

    printf( "The number of pairs of equal elements is %zu\n", total );

    return 0; 
}

The program output is

The number of pairs of equal elements is 3

In C++ you can use for example the following alternative approach using the standard container std::map or std::unordered_map.

#include <iostream> 
#include <map> 

int main()  
{ 
    int a[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };
    size_t total = 0; 

    std::map<int, size_t> m; 

    for ( const auto &item : a ) ++m[item]; 

    for ( const auto &item : m ) total += item.second / 2; 

    std::cout << "The number of pairs of equal elements is " << total << '\n'; 

    return 0; 
}

The program output is the same as shown above.

The number of pairs of equal elements is 3
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

And here the C++ solution.

Same approach as Vlad. Simply count the groups of all values and divide this counter by 2, because we are lokking for pairs.

Then count the overall counts:

#include <iostream>
#include <map>
#include <algorithm>
#include <numeric>


int main() {
    // The data
    int arr[] = { 10, 20, 20, 10, 10, 30, 50, 10, 20 };

    // The counter for occurences of one value in the array
    std::map<int, size_t> counter{};

    // Do Count
    for (int i : arr) counter[i]++;

    // Devide all counts by 2. Thats, because we are looking for pairs
    std::for_each(counter.begin(), counter.end(), [](auto& p) { p.second /= 2;});

    // Calculate the overall sum
    size_t pairCounter = std::accumulate(counter.begin(), counter.end(), 0U,
        [](const size_t v, const auto& p) { return v + p.second; });

    std::cout << "\nNumber of pairs: " << pairCounter << "\n";

    return 0;
}
A M
  • 14,694
  • 5
  • 19
  • 44