Skip to content

Commit ca73699

Browse files
authored
Add Job Sequencing in Tcl (#5062)
1 parent 355b4af commit ca73699

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

archive/t/tcl/job-sequencing.tcl

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package require math
2+
3+
proc usage {} {
4+
puts stderr {Usage: please provide a list of profits and a list of deadlines}
5+
exit 1
6+
}
7+
8+
proc parseList {s} {
9+
set tokens [split [string trim $s] ","]
10+
if {[llength $tokens] < 2} { usage }
11+
12+
set result {}
13+
foreach token $tokens {
14+
set t [string trim $token]
15+
if {$t eq "" || [catch {expr {int($t)}} val]} usage
16+
lappend result $val
17+
}
18+
return $result
19+
}
20+
21+
proc compareJobs {a b} {
22+
lassign $a _ aProfit aDeadline
23+
lassign $b _ bProfit bDeadline
24+
25+
expr {
26+
($aProfit > $bProfit) ? -1 :
27+
($aProfit < $bProfit) ? 1 :
28+
($aDeadline > $bDeadline) ? -1 :
29+
($aDeadline < $bDeadline) ? 1 : 0
30+
}
31+
32+
}
33+
34+
proc jobSequencing {profits deadlines} {
35+
if {[llength $profits] != [llength $deadlines]} { usage }
36+
37+
set jobs {}
38+
for {set i 0} {$i < [llength $profits]} {incr i} {
39+
set jobId [expr {$i + 1}]
40+
set profit [lindex $profits $i]
41+
set deadline [lindex $deadlines $i]
42+
lappend jobs [list $jobId $profit $deadline]
43+
}
44+
45+
set jobs [lsort -command compareJobs $jobs]
46+
set maxDeadline [math::max {*}$deadlines]
47+
set slots [lrepeat $maxDeadline 0]
48+
set totalProfit 0
49+
50+
foreach job $jobs {
51+
lassign $job jobId profit deadline
52+
set slotIndex [expr {$deadline - 1}]
53+
while {$slotIndex >= 0 && [lindex $slots $slotIndex]} {
54+
incr slotIndex -1
55+
}
56+
if {$slotIndex >= 0} {
57+
lset slots $slotIndex 1
58+
incr totalProfit $profit
59+
}
60+
}
61+
return $totalProfit
62+
}
63+
64+
if {$argc != 2} {
65+
usage
66+
}
67+
68+
set profits [parseList [lindex $argv 0]]
69+
set deadlines [parseList [lindex $argv 1]]
70+
71+
puts [jobSequencing $profits $deadlines]
72+

0 commit comments

Comments
 (0)