~rbn/fit

2a06b6c08fd0059462ec47893d1fcb8bc13a3ac7 — Ruben Schuller 1 year, 7 months ago 47b2e2b
only create bin in newBin, remove adding of item
3 files changed, 65 insertions(+), 5 deletions(-)

M bin.go
A bin_test.go
M strategy.go
M bin.go => bin.go +6 -2
@@ 15,8 15,12 @@ func (b *Bin) fits(i Item) bool {
	return b.size+i.Size <= b.capacity
}

func newBin(capacity int64, i Item) Bin {
	return Bin{items: []Item{i}, size: i.Size, capacity: capacity}
//func newBin(capacity int64, i Item) Bin {
//	return Bin{items: []Item{i}, size: i.Size, capacity: capacity}
//}

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

func (b *Bin) Items() []Item {

A bin_test.go => bin_test.go +50 -0
@@ 0,0 1,50 @@
package fit

import (
	"testing"
	"sort"
)

func TestBinAdd(t *testing.T) {
	b := newBin(10)
	b.add(Item{Size: 3})
	b.add(Item{Size: 4})

	if len(b.items) != 2 {
		t.Fail()
	}

	if b.items[0].Size != 3 || b.items[1].Size != 4 {
		t.Fail()
	}
}

func TestBinFits(t *testing.T) {
	b := newBin(10)
	b.add(Item{Size: 3})
	if b.fits(Item{Size: 8}) {
		t.Fail()
	}

	if !b.fits(Item{Size: 6}) {
		t.Fail()
	}
}

func TestBinItems(t *testing.T) {
	b := newBin(10)
	b.add(Item{Size: 3})
	b.add(Item{Size: 4})
	if b.Items()[0].Size != 3 || b.Items()[1].Size != 4 {
		t.Fail()
	}
}

func TestBinsBySize(t *testing.T) {
	bins := []Bin{Bin{capacity: 3, size: 3},Bin{capacity: 2, size: 2},Bin{capacity: 1, size: 1}}
	sort.Sort(BinsBySize(bins))

	if bins[0].capacity != 1 || bins[1].capacity != 2 || bins[2].capacity != 3 {
		t.Fail()
	}
}

M strategy.go => strategy.go +9 -3
@@ 12,7 12,9 @@ func First(bins []Bin, capacity int64, x Item) []Bin {
		bins[i].add(x)
		return bins
	}
	bins = append(bins, newBin(capacity, x))
	n := newBin(capacity)
	n.add(x)
	bins = append(bins, n)
	return bins
}



@@ 25,7 27,9 @@ func Best(bins []Bin, capacity int64, x Item) []Bin {
		bins[i].add(x)
		return bins
	}
	bins = append(bins, newBin(capacity, x))
	n := newBin(capacity)
	n.add(x)
	bins = append(bins, n)
	return bins
}



@@ 38,7 42,9 @@ func Worst(bins []Bin, capacity int64, x Item) []Bin {
		bins[i].add(x)
		return bins
	}
	bins = append(bins, newBin(capacity, x))
	n := newBin(capacity)
	n.add(x)
	bins = append(bins, n)
	return bins
}