Repository navigation
Expand file tree
/
Copy pathpacker.go
More file actions
135 lines (108 loc) · 2.43 KB
/
Copy pathpacker.go
File metadata and controls
135 lines (108 loc) · 2.43 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package boxpacker3
import (
"context"
"time"
)
type Option func(*Packer)
func WithAlgorithm(algorithm Algorithm) Option {
return func(p *Packer) {
if algorithm != nil {
p.algorithm = algorithm
}
}
}
func WithRules(rules Rules) Option {
return func(p *Packer) {
p.rules = p.rules.merged(rules.clamped())
}
}
func WithFinishers(finishers ...Finisher) Option {
return func(p *Packer) {
p.finishers = compactFinishers(finishers)
}
}
func WithMerit(merit Merit) Option {
return func(p *Packer) {
if merit != nil {
p.rules.Merit = merit
}
}
}
func WithFiller(filler Filler) Option {
return func(p *Packer) {
if filler != nil {
p.rules.Filler = filler
}
}
}
func WithBudget(budget Budget) Option {
return func(p *Packer) {
p.budget = budget
}
}
func WithObserver(observer Observer) Option {
return func(p *Packer) {
p.observer = observer
}
}
func compactFinishers(finishers []Finisher) []Finisher {
kept := make([]Finisher, 0, len(finishers))
for _, finisher := range finishers {
if finisher != nil {
kept = append(kept, finisher)
}
}
return kept
}
type Packer struct {
algorithm Algorithm
rules Rules
finishers []Finisher
budget Budget
observer Observer
}
func NewPacker(opts ...Option) *Packer {
p := &Packer{
algorithm: NewGreedy(OrderDecreasing, SelectFullestBox),
rules: Rules{},
finishers: DefaultFinishers(),
budget: Budget{},
observer: nil,
}
for _, opt := range opts {
opt(p)
}
return p
}
func (p *Packer) Algorithm() Algorithm { //nolint:ireturn // it hands back what it was given.
return p.algorithm
}
func (p *Packer) Rules() Rules {
return p.rules
}
func (p *Packer) Finishers() []Finisher {
return compactFinishers(p.finishers)
}
func (p *Packer) Budget() Budget {
return p.budget
}
func (p *Packer) problem(boxes []*Box, items []*Item) *Problem {
return newProblem(compact(boxes), piecesOf(items), p.rules, p.finishers, p.budget, p.observer)
}
func (p *Packer) Pack(ctx context.Context, boxes []*Box, items []*Item) (*Result, error) {
started := time.Now()
problem := p.problem(boxes, items)
budgeted, done := p.budget.apply(ctx)
defer done()
packing, err := p.algorithm.Pack(budgeted, problem)
if err != nil {
return nil, err
}
packing, err = problem.finish(budgeted, packing)
if err != nil {
return nil, err
}
result := packing.result()
result.Report = problem.report(p.algorithm.Name(), started, result, packing)
return result, nil
}