~rbn/fit

ref: 257085b3f4eff0bdc980dac54db6d92a71c24621 fit/bin.go -rw-r--r-- 1019 bytes
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
package fit

import (
	"fmt"
)

//Bin is a collection of items requiring at most a given size.
type Bin struct {
	items    []Item
	size     int64
	capacity int64
}

//add a new item to the bin.
func (b *Bin) add(i Item) error {
	if !b.fits(i) {
		return fmt.Errorf("item doesn't fit bin")
	}
	b.items = append(b.items, i)
	b.size += i.Size()
	return nil
}

//fits checks if the items can be put into the bin.
func (b *Bin) fits(i Item) bool {
	return b.size+i.Size() <= b.capacity
}

//newBin allocates a new Bin ready to use.
func newBin(capacity int64) Bin {
	return Bin{capacity: capacity, items: []Item{}}
}

//Items returns the Items stored in the bin.
func (b *Bin) Items() []Item {
	return b.items
}

//BinsBySize implements sort.Interface, sorting Bins by the size of the contained items.
type BinsBySize []Bin

func (x BinsBySize) Len() int           { return len(x) }
func (x BinsBySize) Less(i, j int) bool { return x[i].size < x[j].size }
func (x BinsBySize) Swap(i, j int)      { x[i], x[j] = x[j], x[i] }