Created
February 6, 2018 09:44
-
-
Save juanfal/3ced93b10c75a33a7ff9706df4543556 to your computer and use it in GitHub Desktop.
dominator of an array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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