-
Notifications
You must be signed in to change notification settings - Fork 4
/
solution_construction_random.go
91 lines (75 loc) · 2.02 KB
/
solution_construction_random.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
// © 2019-present nextmv.io inc
package nextroute
import (
"context"
"github.com/nextmv-io/nextroute/common"
)
// NewRandomSolution returns a random solution for the given model.
func NewRandomSolution(ctx context.Context, model Model) (Solution, error) {
solution, err := NewSolution(model)
if err != nil {
return nil, err
}
return RandomSolutionConstruction(ctx, solution)
}
// RandomSolutionConstruction returns a random solution by populating the
// empty input with a random plan unit. The remaining plan units
// are added to the solution in a random order at the best possible position.
func RandomSolutionConstruction(ctx context.Context, s Solution) (Solution, error) {
solution := s.Copy()
emptyVehicles := common.Filter(
solution.Vehicles(),
func(v SolutionVehicle) bool {
return v.IsEmpty()
},
)
LoopVehicles:
for _, vehicle := range emptyVehicles {
unplannedPlanUnits := NewSolutionPlanUnitCollection(
solution.Random(),
solution.UnPlannedPlanUnits().SolutionPlanUnits(),
)
UnplannedUnitsLoop:
for unplannedPlanUnits.Size() > 0 {
select {
case <-ctx.Done():
break LoopVehicles
default:
unplannedPlanUnit := unplannedPlanUnits.RandomElement()
m := vehicle.BestMove(ctx, unplannedPlanUnit)
if m.IsImprovement() {
result, err := m.Execute(ctx)
if err != nil {
return nil, err
}
if result {
break UnplannedUnitsLoop
}
}
unplannedPlanUnits.Remove(unplannedPlanUnit)
}
}
}
unplannedPlanUnits := NewSolutionPlanUnitCollection(
solution.Random(),
solution.UnPlannedPlanUnits().SolutionPlanUnits(),
)
LoopUnplannedPlanUnits:
for unplannedPlanUnits.Size() > 0 {
select {
case <-ctx.Done():
break LoopUnplannedPlanUnits
default:
unplannedPlanUnit := unplannedPlanUnits.RandomElement()
m := solution.BestMove(ctx, unplannedPlanUnit)
if m.IsImprovement() {
_, err := m.Execute(ctx)
if err != nil {
return nil, err
}
}
unplannedPlanUnits.Remove(unplannedPlanUnit)
}
}
return solution, nil
}