How to find pairs of neighboring and non-neighboring elements in an unordered array?

Example: 10 20 20 10 10 30 50 10 20 . The pairs here are 10-10 , 10-10 , 20-20 . That is only 3 pairs.

As I understand it, you first need to sort the array in order to search for neighboring elements by it. It takes only 4 \ 7 tests. What is the problem?

 #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, count = 0; cin >> n; vector<int> c(n); for (int i = 0; i < n; i++) { cin >> c[i]; } sort(c.begin(), c.end()); for (int i = 0; i < n - 1; i++) { if (c[i] == c[i + 1]) { count++; } } if (count % 2 == 0) { count /= 2; } else if (count % 2 != 0) { count++; count /= 2; } cout << count; return 0; } 

Closed due to the fact that the essence of the issue is incomprehensible by the participants Harry , pavel , aleksandr barakin , Denis , αλεχολυτ 8 Nov '16 at 9:59 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Formulate the task completely. What would you like? 1 2 3 4 5 - pairs of neighboring 12, 23, 34, 45, non-neighboring 13, 14, 15, 24, 25, 35 - do you need it? :) - Harry
  • @Harry updated the question - phen0menon
  • i++ add to the loop where count++ , and below the division can be removed - J. Doe
  • @ J.Doe understood his mistake .. thank you - phen0menon

2 answers 2

If there is, for example, an array of the form { 10, 10, 10, 10, 20, 20 } , then the count after the loop will be equal to 4, and you will get that there are only 2 pairs of equal elements using the formula count /= 2 .. On in fact, it would be correct to assume 10, 10, 10, 10 == 3 Then (3 + 1) / 2 == 2. The same is here 20, 20 == 1, (1 + 1) / 2 = 1.

With your counting, you lose the remainder of dividing by 2 for each number of identical numbers.

I can offer the following solution

 #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = { 10, 20, 20, 10, 10, 30, 50, 10, 20 }; std::sort( v.begin(), v.end() ); std::vector<int>::size_type count = 0; for ( std::vector<int>::size_type i = 0; ++i < v.size(); ) { if ( v[i] == v[i-1] ) { ++i; ++count; } } std::cout << "count = " << count << std::endl; return 0; } 

For a given array, the output to the program console will be

 count = 3 

    As an option :)

     #include <map> #include <iostream> using namespace std; int main() { map<int,int> M; int n, count = 0; cin >> n; for (int i = 0; i < n; i++) { int x; cin >> x; M[x]++; } for(auto x: M) { if (x.second > 1) // Эту строку можно и выкинуть :) count += x.second/2; } cout << count; return 0; }