diff --git a/src/algorithms/sorting/scheduling.h b/src/algorithms/sorting/scheduling.h new file mode 100644 index 00000000..05c433bb --- /dev/null +++ b/src/algorithms/sorting/scheduling.h @@ -0,0 +1,39 @@ +#ifndef SCHEDULING_H +#define SCHEDULING_H + +#ifdef __cplusplus +#include +#include +#include +#endif + +/** +* @brief scheduling function +* @details Returns the maximum jobs that can be completed in a schedule with pairs (x, y) indicating the starting and ending time +* @param intervals: the passed schedule(vector >) +* @return int: the total amount of jobs that can be completed +*/ +int scheduling(std::vector > &intervals) { + std::sort(intervals.begin(), intervals.end(), [&](const std::pair &a, const std::pair &b){ + if(a.second == b.second) { + return a.first < b.first; + } + return a.second < b.second; + }); + + auto [start_x, start_y] = intervals[0]; + int count_valid = 1; + for(int i = 1; i= start_y) { + count_valid++; + start_x = intervals[i].first; + start_y = intervals[i].second; + } + } + + return count_valid; +} + + +#endif diff --git a/tests/algorithms/sorting/scheduling.cc b/tests/algorithms/sorting/scheduling.cc new file mode 100644 index 00000000..a84fcb3f --- /dev/null +++ b/tests/algorithms/sorting/scheduling.cc @@ -0,0 +1,28 @@ +#include "../../../src/algorithms/sorting/scheduling.h" +#include "../../../third_party/catch.hpp" + +TEST_CASE("Testing scheduling [1]") { + std::vector > v = {{0, 1}, {0, 2}, {1, 2}, {2, 4}}; + + REQUIRE(scheduling(v) == 3); + + v.clear(); + v = {{0, 3}, {2, 5}, {3, 9}, {7, 8}}; + + REQUIRE(scheduling(v) == 2); + + v.clear(); + v = {{1, 2}, {2, 3}, {4, 5}, {0, 1}}; + + REQUIRE(scheduling(v) == 4); + + v.clear(); + v = {{0, 10}, {2, 3}, {4, 5}}; + + REQUIRE(scheduling(v) == 2); + + v.clear(); + v = {{0, 4}, {3, 5}, {4, 8}}; + + REQUIRE(scheduling(v) == 2); +}