Skip to content

Commit

Permalink
Added scheduling algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Nov 21, 2024
1 parent 4906d75 commit 350578b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/algorithms/sorting/scheduling.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#ifndef SCHEDULING_H
#define SCHEDULING_H

#ifdef __cplusplus
#include <iostream>
#include <algorithm>
#include <vector>
#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<pair<int, int> >)
* @return int: the total amount of jobs that can be completed
*/
int scheduling(std::vector<std::pair<int, int> > &intervals) {
std::sort(intervals.begin(), intervals.end(), [&](const std::pair<int, int> &a, const std::pair<int, int> &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<int(intervals.size()); i++) {
auto [x, y] = intervals[i];
if(x >= start_y) {
count_valid++;
start_x = intervals[i].first;
start_y = intervals[i].second;
}
}

return count_valid;
}


#endif
28 changes: 28 additions & 0 deletions tests/algorithms/sorting/scheduling.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include "../../../src/algorithms/sorting/scheduling.h"
#include "../../../third_party/catch.hpp"

TEST_CASE("Testing scheduling [1]") {
std::vector<std::pair<int, int> > 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);
}

0 comments on commit 350578b

Please sign in to comment.