-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyd_cycle_detection_algo.cpp
53 lines (48 loc) · 1.3 KB
/
floyd_cycle_detection_algo.cpp
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
52
53
#include <cassert>
#include <iostream>
#include <vector>
namespace search {
namespace cycle_detection {
template <typename T>
int32_t duplicateNumber(const std::vector<T> &in_arr, const uint32_t &n) {
if (n == 0 ||
n == 1) {
return -1;
}
uint32_t tortoise = in_arr[0];
uint32_t hare =
in_arr[0];
do {
tortoise = in_arr[tortoise];
hare = in_arr[in_arr[hare]];
} while (tortoise != hare);
tortoise = in_arr[0];
while (tortoise != hare) {
tortoise = in_arr[tortoise];
hare = in_arr[hare];
}
return tortoise;
}
}
}
static void test() {
std::vector<uint32_t> array1 = {3, 4, 8, 5, 9, 1, 2, 6, 7, 4};
std::cout << "Test 1... ";
assert(search::cycle_detection::duplicateNumber(array1, array1.size()) ==
4);
std::cout << "passed" << std::endl;
std::vector<uint32_t> array2 = {1, 2, 3, 4, 2};
std::cout << "Test 2... ";
assert(search::cycle_detection::duplicateNumber(array2, array2.size()) ==
2);
std::cout << "passed" << std::endl;
std::vector<uint32_t> array3 = {};
std::cout << "Test 3... ";
assert(search::cycle_detection::duplicateNumber(array3, array3.size()) ==
-1);
std::cout << "passed" << std::endl;
}
int main() {
test();
return 0;
}