TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
duval.cpp
Go to the documentation of this file.
1
29#include <array>
30#include <cassert>
31#include <cstddef>
32#include <deque>
33#include <iostream>
34#include <string>
35#include <vector>
36
41namespace string {
48template <typename T>
49size_t duval(const T& s) {
50 size_t n = s.size();
51 size_t i = 0, ans = 0;
52 while (i < n) {
53 ans = i;
54 size_t j = i + 1, k = i;
55 while (j < (n + n) && s[j % n] >= s[k % n]) {
56 if (s[k % n] < s[j % n]) {
57 k = i;
58 } else {
59 k++;
60 }
61 j++;
62 }
63 while (i <= k) {
64 i += j - k;
65 }
66 }
67 return ans;
68 // returns 0-indexed position of the least cyclic shift
69}
70
71} // namespace string
72
77static void test() {
78 using namespace string;
79
80 // Test 1
81 std::string s1 = "abcab";
82 assert(duval(s1) == 3);
83
84 // Test 2
85 std::string s2 = "011100";
86 assert(duval(s2) == 4);
87
88 // Test 3
89 std::vector<int> v = {5, 2, 1, 3, 4};
90 assert(duval(v) == 2);
91
92 // Test 4
93 std::array<int, 5> a = {1, 2, 3, 4, 5};
94 assert(duval(a) == 0);
95
96 // Test 5
97 std::deque<char> d = {'a', 'z', 'c', 'a', 'b'};
98 assert(duval(d) == 3);
99
100 // Test 6
101 std::string s3;
102 assert(duval(s3) == 0);
103
104 // Test 7
105 std::vector<int> v2 = {5, 2, 1, 3, -4};
106 assert(duval(v2) == 4);
107
108 std::cout << "All tests passed!" << std::endl;
109}
110
115int main() {
116 test(); // run self test implementations
117 return 0;
118}
static void test()
self test implementation returns void
Definition duval.cpp:77
int main()
main function
Definition duval.cpp:115
string manipulation algorithms
Definition duval.cpp:41
size_t duval(const T &s)
Find the lexicographically smallest cyclic shift of a sequence.
Definition duval.cpp:49