~rbn/fit

ref: d4e952d1ef97f706723c91cd9a76734bafb01662 fit/bin.go -rw-r--r-- 694 bytes 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
package fit

import (
	"fmt"
)

type Bin struct {
	items    []Item
	size     int64
	capacity int64
}

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
}

func (b *Bin) fits(i Item) bool {
	return b.size+i.Size <= b.capacity
}

func newBin(capacity int64) Bin {
	return Bin{capacity: capacity, items: []Item{}}
}

func (b *Bin) Items() []Item {
	return b.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] }