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] }