さて、私のprintfステートメントがある行に「エラー:「OTHER」トークンの前に一次式が必要です」というメッセージが表示されます。私はこの問題を調査しましたが、何が起こっているのかまだわかりません。ところで、私のプログラムがどうあるべきか疑問に思われている方のために、私は 2 つの異なる方法を使用して、整数配列内で最も頻度の高い要素を見つけるのにかかる時間の平均差を計算しようとしています。最初の方法は単なる O(n^2) の強引な方法で、もう 1 つは配列の要素をバイナリ ツリーに入れ、各要素が追加された回数のカウンターを保持します。
#include <stdio.h>
#include <ctime>
#include <time.h>
#include "binArr.h" // Homemade binary tree class with the end of each branch containing a counter
// for how many times it has been reached.
// O(n^2) algorithm: Loop through array and count the number of each element
// by looping through again and checking every other element
// against it, updating, if necessary, a variable for the
// highest count and another for the corresponding element.
int mode (int* arr, int n) {
int most = arr[0];
unsigned mostCnt = 0;
for (unsigned i = 0; i < n; i++) {
int thisCnt = 0;
for (unsigned j = 0; j < n; j++) {
if (arr[j] == arr[i]) thisCnt++;
}
if (thisCnt > mostCnt) {
mostCnt = thisCnt;
most = arr[i];
}
}
return most;
}
void test_efficiency(const unsigned max_array_test_size, const unsigned tests_per_size) {
srand (time(NULL));
double avgTimeDiff = 0;
for (unsigned i = 1; i <= max_array_test_size; i++) {
int arr[i];
for (unsigned j = 0; j < i; j++) {
for (unsigned k = 0; k < tests_per_size; k++) {
for (unsigned m = 0; m < i; m++) arr[m] = rand() % j + 1;
}
clock_t start, stop;
double method1Time, method2Time;
start = clock();
int thisMode = mode(arr, sizeof(arr)/sizeof(int));
stop = clock();
method1Time = (stop - start) / CLOCKS_PER_SEC;
start = clock();
binArr B;
B.addArray(sizeof(arr)/sizeof(int), arr);
thisMode = B.getMost();
stop = clock();
method2Time = (stop - start) / CLOCKS_PER_SEC;
avgTimeDiff += method2Time - method1Time;
}
}
avgTimeDiff /= (max_array_test_size * max_array_test_size * tests_per_size);
printf("After %c tests, testing arrays up to a size of %c, \n
the average time difference between the brute force \n
method and binary tree method to find the mode of \n
an integer array is %f seconds",
tests_per_size, max_array_test_size, avgTimeDiff);
}
int main() {
const unsigned TESTS_PER_SIZE = 500; // Number of tests to be executed
const unsigned MAX_ARRAY_TEST_SIZE = 50; // Array size per test
test_efficiency(MAX_ARRAY_TEST_SIZE, TESTS_PER_SIZE);
/*
int arr[] = {9, 3, 2, 11, 87, 4, 3, 3, 3, 3, 3, 9, 21, 11, 91, 11, 9, 2, 9};
// Using the binary tree
binArr B;
B.addArray(sizeof(arr)/sizeof(int), arr);
std::cout << "The mode of arr, using the binary tree, is " << B.getMost() << std::endl;
// Using the basic O(n^2) algorithm
std::cout << "The mode of arr, using the binary tree, is " << mode(arr, sizeof(arr)/sizeof(int));
*/
return 0;
}