Kodewick
Start learning →
Mini challenge←→0 / 70

Camping backpack

#066Mini challengeStructsSlices7 min

For a camping trip the backpack can carry at most limit kg. Go through items in order: if adding one keeps you within the limit, pack it; if not, skip it and look at the next. Write Pack(items, limit) to return the names packed and the total weight.

Examples
Pack([]Item{{"tent", 5}, {"stove", 2}, {"chair", 4}}, 8)→(['tent', 'stove'], 7)
Pack([]Item{}, 10)→([], 0)
The functionfunc Pack(items []Item, limit int) ([]string, int)
main.go
package main

type Item struct {
	Name string
	Kg   int
}

func Pack(items []Item, limit int) ([]string, int) {
	packed := []string{}
	total := 0
	for _, it := range items {
		// your code here: if it fits under the limit, add it to packed and to total
	}
	return packed, total
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.