~rbn/fit

ff958a71704b66f0a5ce4f47ce1af26092cc450c — Ruben Schuller 1 year, 2 months ago 8e42e73
add example
5 files changed, 50 insertions(+), 3 deletions(-)

M bin_test.go
M item.go
A item_test.go
A pack_test.go
M select_test.go
M bin_test.go => bin_test.go +2 -2
@@ 1,8 1,8 @@
package fit

import (
	"testing"
	"sort"
	"testing"
)

func TestBinAdd(t *testing.T) {


@@ 48,7 48,7 @@ func TestBinItems(t *testing.T) {
}

func TestBinsBySize(t *testing.T) {
	bins := []Bin{Bin{capacity: 3, size: 3},Bin{capacity: 2, size: 2},Bin{capacity: 1, size: 1}}
	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 {

M item.go => item.go +1 -0
@@ 1,5 1,6 @@
package fit

//Item interface has to be implemented by the items which should be packed.
type Item interface {
	Size() int64
}

A item_test.go => item_test.go +10 -0
@@ 0,0 1,10 @@
package fit

type ExampleItem struct {
	data string
	size int64
}

func (e *ExampleItem) Size() int64 {
	return e.size
}

A pack_test.go => pack_test.go +36 -0
@@ 0,0 1,36 @@
package fit

import (
	"fmt"
	"sort"
)

func ExamplePack() {
	items := []Item{
		&ExampleItem{data: "first item", size: 4},
		&ExampleItem{data: "second item", size: 2},
		&ExampleItem{data: "third item", size: 6},
		&ExampleItem{data: "fourth item", size: 5},
	}

	// sort biggest items first
	sort.Sort(sort.Reverse(ItemsBySize(items)))

	// pack into bins selecting the best fitting bin
	bins, err := Pack(Best, 10, items)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, bin := range bins {
		for _, item := range bin.Items() {
			fmt.Println(item.(*ExampleItem).data)
		}
	}
	//Output:
	//third item
	//first item
	//fourth item
	//second item
}

M select_test.go => select_test.go +1 -1
@@ 110,7 110,7 @@ func testSelect(t *testing.T, binSelect BinSelectFunc, tests []selectTest) {
		if err != nil {
			t.FailNow()
		}
		t.Logf("%#v",bins)
		t.Logf("%#v", bins)

		binItem := bins[test.bin].Items()[test.pos]
		if binItem.Size() != test.item.Size() {