~rbn/fit

ref: 257085b3f4eff0bdc980dac54db6d92a71c24621 fit/select.go -rw-r--r-- 1.3 KiB
257085b3Ruben Schuller go.mod whoops 7 months ago
                                                                                
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
package fit

import (
	"sort"
)

//First places the Item into the first Bin in which it fits.
func First(bins []Bin, capacity int64, x Item) ([]Bin, error) {
	for i, b := range bins {
		if !b.fits(x) {
			continue
		}
		bins[i].add(x)
		return bins, nil
	}
	n := newBin(capacity)
	err := n.add(x)
	if err != nil {
		return nil, err
	}
	bins = append(bins, n)
	return bins, nil
}

//Best places the Item into the fullest Bin it fits.
func Best(bins []Bin, capacity int64, x Item) ([]Bin, error) {
	sort.Sort(sort.Reverse(BinsBySize(bins)))
	for i, b := range bins {
		if !b.fits(x) {
			continue
		}
		err := bins[i].add(x)
		if err != nil {
			return nil, err
		}
		return bins, nil
	}
	n := newBin(capacity)
	n.add(x)
	bins = append(bins, n)
	return bins, nil
}

//Worst places the Item into the least full Bin in which it fits.
func Worst(bins []Bin, capacity int64, x Item) ([]Bin, error) {
	sort.Sort(BinsBySize(bins))
	for i, b := range bins {
		if !b.fits(x) {
			continue
		}
		err := bins[i].add(x)
		if err != nil {
			return nil, err
		}
		return bins, nil
	}
	n := newBin(capacity)
	n.add(x)
	bins = append(bins, n)
	return bins, nil
}

//BinSelectFunc is a strategy for placing an item into one of the bins.
//
//If required, a new bin is added with the given capacity.
type BinSelectFunc func(bins []Bin, capacity int64, item Item) ([]Bin, error)