Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created February 6, 2018 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanfal/3ced93b10c75a33a7ff9706df4543556 to your computer and use it in GitHub Desktop.
Save juanfal/3ced93b10c75a33a7ff9706df4543556 to your computer and use it in GitHub Desktop.
dominator of an array
// 01.dominator.cpp
// juanfc 2018-02-06
#include <iostream>
#include <array>
using namespace std;
const int N = 9;
typedef array<int,N> TVec;
int dominator(TVec a);
int main() {
TVec a1 = {{3,4,3,2,3,1,3,3,1}},
a2 = {{4,4,3,2,3,1,3,3,1}},
a3 = {{1,3,2,1,4,4,4,4,4}};
cout << "The dominator of a1 is: "
<< dominator(a1) << endl;
cout << "The dominator of a2 is: "
<< dominator(a2) << endl;
cout << "The dominator of a3 is: "
<< dominator(a3) << endl;
return 0;
}
int count(TVec a, int x);
int dominator(TVec a) {
int i = 0;
int r = -1;
int midpoint = a.size()/2;
while (i <= midpoint and count(a, a[i]) <= N/2)
++i;
if (i <= midpoint)
r = a[i];
return r;
}
int count(TVec a, int x)
{
int cnt = 0;
for (int i = 0; i < a.size(); ++i)
if (a[i] == x)
++cnt;
return cnt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment