-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschedulingJobs.go
106 lines (93 loc) · 2.13 KB
/
schedulingJobs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
)
type job struct {
weight int
length int
difference int
ratio float64
completion int
}
func scheduleJobs(elements []job, sortbyDif bool) int {
if sortbyDif {
sort.Sort(byDifference(elements))
} else {
sort.Sort(byRatio(elements))
}
return sum(calcCompletionTimes(elements))
}
func calcCompletionTimes(elements []job) []job {
currentTime := 0
for i, v := range elements {
currentTime += v.length
v.completion = currentTime
elements[i] = v
}
return elements
}
func sum(elements []job) int {
sum := 0
for _, v := range elements {
sum += (v.completion * v.weight)
}
return sum
}
// byDifference is a sort api
type byDifference []job
func (bd byDifference) Len() int { return len(bd) }
func (bd byDifference) Less(i, j int) bool {
if bd[i].difference == bd[j].difference {
return bd[i].weight > bd[j].weight
}
return bd[i].difference > bd[j].difference
}
func (bd byDifference) Swap(i, j int) { bd[i], bd[j] = bd[j], bd[i] }
// byRatio is a sort api
type byRatio []job
func (br byRatio) Len() int { return len(br) }
func (br byRatio) Less(i, j int) bool { return br[i].ratio > br[j].ratio }
func (br byRatio) Swap(i, j int) { br[i], br[j] = br[j], br[i] }
func main() {
fmt.Println(scheduleJobs(loadData("./course3/week1/schedulingJobs/data.txt"), false))
}
func loadData(filepath string) []job {
data := make([]job, 0, 10000)
f, err := os.Open(filepath)
check(err)
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
parseRowIntoEntry(&data, scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return data
}
func parseRowIntoEntry(container *[]job, row string) {
rowSlice := strings.Fields(row)
if len(rowSlice) > 1 {
weight, err := strconv.Atoi(rowSlice[0])
check(err)
length, err := strconv.Atoi(rowSlice[1])
check(err)
*container = append(*container, job{
weight: weight,
length: length,
difference: weight - length,
ratio: float64(weight) / float64(length),
})
}
}
func check(err error) {
if err != nil {
log.Panicln(err)
}
}