File tree Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Expand file tree Collapse file tree 2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1+ mod job_sequencing;
12mod stable_matching;
23
4+ pub use self :: job_sequencing:: job_sequencing;
35pub use self :: stable_matching:: stable_matching;
You can’t perform that action at this time.
0 commit comments