This repository has been archived by the owner on Mar 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elevators.go
53 lines (44 loc) · 1.67 KB
/
elevators.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
package mesoelevator
import(
"sort"
)
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ById []*Elevator
func (a ById) Len() int { return len(a) }
func (a ById) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ById) Less(i, j int) bool { return a[i].id < a[j].id }
type Elevators []*Elevator
// NOTE: not thread-safe, but it does not need to be thread-safe.
// It's simple for loop to initialize the list. This should get call at the very beginning to setup
// the elevator list.
func NewElevators(size int)(Elevators){
var elevators Elevators
for i := 1; i <= size; i++ {
elevator := NewElevator(i)
elevators = append(elevators, elevator)
}
return elevators
}
// It does a binary search to find the elevator element by its Id and return the index position
func (es Elevators) FindId(id int)(int){
sort.Sort(ById(es)) //assuming that slice is not always sorted
return sort.Search(len(es), func(i int) bool {
return es[i].id >= id
})
}
// NOTE: not thread-safe, but it does not need to be thread-safe. It's a read-only function and
// should only be used for reporting purpose.
func (es Elevators) Flatten()([][]int){
var slice [][]int
for _, elevator := range es {
// type assertion for slices from interface{} to int
goals := make([]int, elevator.goalFloors.Size())
for i, floor := range elevator.goalFloors.List() { goals[i] = floor.(int) }
elevatorStatus := []int{elevator.id, elevator.currentFloor, elevator.direction}
//flatten goal floors into 1 slice and added
elevatorStatus = append(elevatorStatus, goals...)
slice = append(slice, elevatorStatus )
}
return slice
}