~rbn/fit

ref: d4e952d1ef97f706723c91cd9a76734bafb01662 fit/strategy.go -rw-r--r-- 1.0 KiB View raw
d4e952d1Ruben Schuller return errors for bin methods 1 year, 5 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
package fit

import (
	"sort"
)

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
}

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
}

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
}

type StrategyFunc func([]Bin, int64, Item) ([]Bin, error)