11#pragma once
22
33#include < string>
4- #include < set>
54#include < tuple>
6- #include < regex>
75#include < random>
8- #include < utility>
9-
10- #include " data.hpp"
116
127namespace oryx ::chron {
138class Randomization {
@@ -21,68 +16,8 @@ class Randomization {
2116 auto Parse (const std::string& cron_schedule) -> std::tuple<bool, std::string>;
2217
2318private:
24- template <typename T>
25- auto GetRandomInRange (const std::string& section,
26- int & selected_value,
27- std::pair<int , int > limit = std::make_pair(-1 , -1 )) -> std::pair<bool, std::string>;
28-
29- auto DayLimiter (const std::set<Months>& month) -> std::pair<int, int>;
30- auto Cap (int value, int lower, int upper) -> int;
31-
32- // Members
33- const std::regex rand_expression_{R"#( [rR]\((\d+)\-(\d+)\))#" , std::regex_constants::ECMAScript};
3419 std::random_device random_device_;
3520 std::mt19937 twister_;
3621};
3722
38- template <typename T>
39- auto Randomization::GetRandomInRange (const std::string& section, int & selected_value, std::pair<int , int > limit)
40- -> std::pair<bool, std::string> {
41- auto result = std::make_pair (true , std::string{});
42- selected_value = -1 ;
43-
44- std::smatch random_match;
45-
46- if (std::regex_match (section.cbegin (), section.cend (), random_match, rand_expression_)) {
47- // Random range, parse left and right numbers
48- auto left = std::stoi (random_match[1 ].str ());
49- auto right = std::stoi (random_match[2 ].str ());
50-
51- // Apply limit if provided
52- if (limit.first != -1 && limit.second != -1 ) {
53- left = Cap (left, limit.first , limit.second );
54- right = Cap (right, limit.first , limit.second );
55- }
56-
57- Data cron_data;
58- std::set<T> numbers;
59- result.first = cron_data.ConvertFromStringRangeToNumberRange <T>(
60- std::to_string (left) + " -" + std::to_string (right), numbers);
61-
62- // Remove items outside the limit
63- if (limit.first != -1 && limit.second != -1 ) {
64- for (auto it = numbers.begin (); it != numbers.end ();) {
65- if (Data::ValueOf (*it) < limit.first || Data::ValueOf (*it) > limit.second ) {
66- it = numbers.erase (it);
67- } else {
68- ++it;
69- }
70- }
71- }
72-
73- if (result.first && !numbers.empty ()) {
74- // Select a random value from the valid numbers
75- std::uniform_int_distribution<> distribution (0 , static_cast <int >(numbers.size () - 1 ));
76- auto it = numbers.begin ();
77- std::advance (it, distribution (twister_));
78- selected_value = Data::ValueOf (*it);
79- result.second = std::to_string (selected_value);
80- }
81- } else {
82- // Not a random section, return as-is
83- result.second = section;
84- }
85-
86- return result;
87- }
8823} // namespace oryx::chron
0 commit comments