Knapsack

Knapsack

Medium

Introduction

Lhakpa is a Sherpa mountain guide and porter. After months of careful planning, the expedition Lhakpa works for is about to leave. She will be paid the value she carried to the base camp.

In front of her are many items, each with a value and weight. Lhakpa would gladly take all of the items, but her knapsack can only hold so much weight.

Instructions

Your task is to determine which items to take so that the total value of her selection is maximized, taking into account the knapsack's carrying capacity.

Items will be represented as a list of items. Each item will have a weight and value. All values given will be strictly positive. Lhakpa can take only one of each item.

For example:

Items: [
  { "weight": 5, "value": 10 },
  { "weight": 4, "value": 40 },
  { "weight": 6, "value": 30 },
  { "weight": 4, "value": 50 }
]

Knapsack Maximum Weight: 10

For the above, the first item has weight 5 and value 10, the second item has weight 4 and value 40, and so on. In this example, Lhakpa should take the second and fourth item to maximize her value, which, in this case, is 90. She cannot get more than 90 as her knapsack has a weight limit of 10.

The items are represented by records, defined in item.lfe. Use item-weight to get the weight and item-value to get the value.

;; Create an item with weight=5, value=50
(set item (make-item weight 5 value 50))

;; Get the weight. Returns 5.
(item-weight item)

;; Get the value. Returns 50.
(item-value item)

Source

WikipediaThe link opens in a new window or tab
Edit via GitHub The link opens in a new window or tab
Lisp Flavoured Erlang Exercism

Ready to start Knapsack?

Sign up to Exercism to learn and master Lisp Flavoured Erlang with 62 exercises, and real human mentoring, all for free.