用GO语言写一个装箱算法
时间: 2024-04-29 12:21:14 浏览: 187
以下是一个简单的装箱算法,用Go语言实现。该算法将物品分配到不同的箱子中,以最小化箱子数量。
```
package main
import (
"fmt"
"sort"
)
type Item struct {
weight int
}
type Box struct {
items []Item
weight int
maxLoad int
}
func (b *Box) canFit(item Item) bool {
return b.weight+item.weight <= b.maxLoad
}
func (b *Box) addItem(item Item) {
b.items = append(b.items, item)
b.weight += item.weight
}
func packItems(items []Item, maxLoad int) []Box {
sort.Slice(items, func(i, j int) bool {
return items[i].weight > items[j].weight
})
boxes := []Box{}
for _, item := range items {
var box *Box
for i := range boxes {
if boxes[i].canFit(item) {
box = &boxes[i]
break
}
}
if box == nil {
box = &Box{
maxLoad: maxLoad,
}
boxes = append(boxes, *box)
}
box.addItem(item)
}
return boxes
}
func main() {
items := []Item{
{weight: 10},
{weight: 5},
{weight: 2},
{weight: 8},
{weight: 3},
}
maxLoad := 10
boxes := packItems(items, maxLoad)
fmt.Printf("Packed %d items into %d boxes:\n", len(items), len(boxes))
for i, box := range boxes {
fmt.Printf("Box %d: %v\n", i+1, box.items)
}
}
```
该算法首先按重量将物品排序。然后,它遍历每个物品,并尝试将其放入现有箱子中,如果找不到适合的箱子,则创建一个新的箱子。最后,它返回包含所有箱子的列表。
阅读全文