-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
search_entry_equal_to_index.cc
51 lines (43 loc) · 1.44 KB
/
search_entry_equal_to_index.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <vector>
#include "test_framework/generic_test.h"
#include "test_framework/test_failure.h"
#include "test_framework/timed_executor.h"
using std::vector;
int SearchEntryEqualToItsIndex(const vector<int>& A) {
int left = 0, right = size(A) - 1;
while (left <= right) {
int mid = left + ((right - left) / 2);
// A[mid] == mid if and only if difference == 0.
if (int difference = A[mid] - mid; difference == 0) {
return mid;
} else if (difference > 0) {
right = mid - 1;
} else { // difference < 0.
left = mid + 1;
}
}
return -1;
}
void SearchEntryEqualToItsIndexWrapper(TimedExecutor& executor,
const vector<int>& A) {
int result = executor.Run([&] { return SearchEntryEqualToItsIndex(A); });
if (result != -1) {
if (A[result] != result) {
throw TestFailure("Entry does not equal to its index");
}
} else {
for (int i = 0; i < A.size(); ++i) {
if (A[i] == i) {
throw TestFailure("There are entries which equal to its index");
}
}
}
}
// clang-format off
int main(int argc, char* argv[]) {
std::vector<std::string> args {argv + 1, argv + argc};
std::vector<std::string> param_names {"executor", "A"};
return GenericTestMain(args, "search_entry_equal_to_index.cc", "search_entry_equal_to_index.tsv", &SearchEntryEqualToItsIndexWrapper,
DefaultComparator{}, param_names);
}
// clang-format on