Skip to content

Commit 4759b36

Browse files
committed
added job sequening
1 parent ed7a42e commit 4759b36

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

src/greedy/job_sequencing.rs

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
use std::collections::HashMap;
2+
3+
#[derive(Debug, Clone)]
4+
pub struct Job {
5+
pub id: String,
6+
pub deadline: usize,
7+
pub profit: i32,
8+
}
9+
10+
pub fn job_sequencing(mut jobs: Vec<Job>) -> (Vec<Job>, i32) {
11+
if jobs.is_empty() {
12+
return (Vec::new(), 0);
13+
}
14+
15+
// Sort by profit (descending)
16+
jobs.sort_by(|a, b| b.profit.cmp(&a.profit));
17+
18+
// Find the maximum deadline
19+
let max_deadline = jobs.iter().map(|j| j.deadline).max().unwrap();
20+
21+
// Track time slots that are filled
22+
let mut slots = vec![false; max_deadline];
23+
let mut scheduled = Vec::new();
24+
let mut total_profit = 0;
25+
26+
// Schedule each job in the latest available slot before its deadline is reached
27+
for job in jobs {
28+
for slot in (0..job.deadline.min(max_deadline)).rev() {
29+
if !slots[slot] {
30+
slots[slot] = true;
31+
scheduled.push(job.clone());
32+
total_profit += job.profit;
33+
break;
34+
}
35+
}
36+
}
37+
38+
(scheduled, total_profit)
39+
}
40+
41+
// test algorithm
42+
#[cfg(test)]
43+
mod tests {
44+
use super::*;
45+
46+
#[test]
47+
fn test_basic() {
48+
let jobs = vec![
49+
Job {
50+
id: "J1".to_string(),
51+
deadline: 2,
52+
profit: 100,
53+
},
54+
Job {
55+
id: "J2".to_string(),
56+
deadline: 1,
57+
profit: 19,
58+
},
59+
Job {
60+
id: "J3".to_string(),
61+
deadline: 2,
62+
profit: 27,
63+
},
64+
Job {
65+
id: "J4".to_string(),
66+
deadline: 1,
67+
profit: 25,
68+
},
69+
Job {
70+
id: "J5".to_string(),
71+
deadline: 3,
72+
profit: 15,
73+
},
74+
];
75+
76+
let (scheduled, profit) = job_sequencing(jobs);
77+
78+
assert_eq!(profit, 142);
79+
assert_eq!(scheduled.len(), 3);
80+
}
81+
82+
#[test]
83+
fn test_empty() {
84+
let (scheduled, profit) = job_sequencing(vec![]);
85+
assert_eq!(profit, 0);
86+
assert!(scheduled.is_empty());
87+
}
88+
}

src/greedy/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
mod job_sequencing;
12
mod stable_matching;
23

4+
pub use self::job_sequencing::job_sequencing;
35
pub use self::stable_matching::stable_matching;

0 commit comments

Comments
 (0)