I am currently interested in implementing statistical measures. Other measures like mean, variance, and covariance are easy, but the mode feels harder than I thought. Is this good enough?
Note: float
is used because I don't really intend to use it on big enough numbers. The size can be changed if needed.
Note 2: We cannot use vectors, any statistical related functions, and any other tool that can impact the performance of the code. What we can use though, are basic data types (int
, float
, double
, bool
, char
, and the long
, short
, and unsigned
versions) and simple conditional and looping structures. To add, the auto
keyword is not allowed.
Probably unrelated, but still relevant: Why did I use "we" instead of "I" in the second note?
I'm still learning C++ in school, so I am limiting myself to what we can do in school even though it can really improve the performance.
#include <iostream>
using std::cout;
using std::cin;
int main () {
int N, uniques = 0, j = 0;
// N: number of elements; uniques: unique elements in list; j: list index
cin >> N;
float list[N], counters[N][2];
// list[N]: the list of elements
// counters[N][2]: the list of unique elements and the number of appearances
bool found = false;
for (int i = 0; i < N; i++) {
cin >> list[i];
found = false;
for (j = 0; j < uniques; j++) {
if (counters[j][0] == list[i]) {
counters[j][1]++;
found = true;
break;
}
}
if (!found) {
counters[uniques][0] = list[i];
counters[uniques][1] = 1;
uniques++;
}
}
int max = counters[0][1], ind = 0, reps = 0;
for (int k = 0; k < uniques; k++) {
if (max == counters[k][1]) {
reps++;
} else if (max < counters[k][1]) {
ind = k, max = counters[k][1];
reps = 1;
}
}
if (reps == 1) {
cout << "The mode of the data set is " << counters[ind][0] << " appearing " << max << " times";
} else {
cout << "undetermined " << reps;
}
return 0;
}
I added comments about the variable names.
cout << "undetermined" << reps;
is just a sanity check if it really counted correctly. \$\endgroup\$