Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add knapsack exercise #227

Merged
merged 2 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,14 @@
"practices": [],
"prerequisites": [],
"difficulty": 8
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "2ef39cbc-801b-437e-96ec-71f3439388e4",
"practices": [],
"prerequisites": [],
"difficulty": 9
}
],
"foregone": [
Expand Down
25 changes: 25 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Instructions

Your task is to determine which items to take so that the total value of his 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.
Bob can take only one of each item.

For example:

```text
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, Bob should take the second and fourth item to maximize his value, which, in this case, is 90.
He cannot get more than 90 as his knapsack has a weight limit of 10.
8 changes: 8 additions & 0 deletions exercises/practice/knapsack/.docs/introduction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Introduction

Bob is a thief.
After months of careful planning, he finally manages to crack the security systems of a fancy store.

In front of him are many items, each with a value and weight.
Bob would gladly take all of the items, but his knapsack can only hold so much weight.
Bob has to carefully consider which items to take so that the total value of his selection is maximized.
19 changes: 19 additions & 0 deletions exercises/practice/knapsack/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"kahgoh"
],
"files": {
"solution": [
"knapsack.asm"
],
"test": [
"knapsack_test.c"
],
"example": [
".meta/example.asm"
]
},
"blurb": "Given a knapsack that can only carry a certain weight, determine which items to put in the knapsack in order to maximize their combined value.",
"source": "Wikipedia",
"source_url": "https://en.wikipedia.org/wiki/Knapsack_problem"
}
74 changes: 74 additions & 0 deletions exercises/practice/knapsack/.meta/example.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
section .text
global maximumValue

maximumValue:
; Argument registers
; %rdi - input items array
; %esi - number of items
; %edx - maximum weight

cmp esi, 0
jg .more

; this must mean there are no items
mov rax, 0
ret

.more:
; Check if there is enough space for the item
mov r10d, dword [rdi + 4]
mov r11, rdx
sub r11d, r10d
js .skip_item

; Next step is to find what value in can get with the item
dec esi
add rdi, 8

; Store the values for the next call
push rdx
push rsi
push rdi

mov edx, r11d

; What value can we get if item was included?
call maximumValue

pop rdi
pop rsi
pop rdx

; Load the item's value to calculate the total value with the item.
; Subtract 8 from rdi because we've already moved it forward to next item.
mov r10d, dword [rdi - 8]
add eax, r10d

push rax

; What value can we get without the item?
call maximumValue

pop r11

; Which value is higher?
cmp rax, r11
jge .return

; Here, the value with the item must be better
mov rax, r11

.return:
ret

.skip_item:
add rdi, 8
dec esi
call maximumValue

ret

%ifidn __OUTPUT_FORMAT__,elf64
section .note.GNU-stack noalloc noexec nowrite progbits
%endif

36 changes: 36 additions & 0 deletions exercises/practice/knapsack/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[a4d7d2f0-ad8a-460c-86f3-88ba709d41a7]
description = "no items"
include = false

[3993a824-c20e-493d-b3c9-ee8a7753ee59]
description = "no items"
reimplements = "a4d7d2f0-ad8a-460c-86f3-88ba709d41a7"

[1d39e98c-6249-4a8b-912f-87cb12e506b0]
description = "one item, too heavy"

[833ea310-6323-44f2-9d27-a278740ffbd8]
description = "five items (cannot be greedy by weight)"

[277cdc52-f835-4c7d-872b-bff17bab2456]
description = "five items (cannot be greedy by value)"

[81d8e679-442b-4f7a-8a59-7278083916c9]
description = "example knapsack"

[f23a2449-d67c-4c26-bf3e-cde020f27ecc]
description = "8 items"

[7c682ae9-c385-4241-a197-d2fa02c81a11]
description = "15 items"
46 changes: 46 additions & 0 deletions exercises/practice/knapsack/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
AS = nasm

CFLAGS = -g -Wall -Wextra -pedantic -Werror
LDFLAGS =
ASFLAGS = -g -F dwarf -Werror

ifeq ($(shell uname -s),Darwin)
ifeq ($(shell sysctl -n hw.optional.arm64 2>/dev/null),1)
ALL_CFLAGS = -target x86_64-apple-darwin
endif
ALL_LDFLAGS = -Wl,-pie -Wl,-fatal_warnings
ALL_ASFLAGS = -f macho64 --prefix _
else
ALL_LDFLAGS = -pie -Wl,--fatal-warnings
ALL_ASFLAGS = -f elf64
endif

ALL_CFLAGS += -std=c99 -fPIE -m64 $(CFLAGS)
ALL_LDFLAGS += $(LDFLAGS)
ALL_ASFLAGS += $(ASFLAGS)

C_OBJS = $(patsubst %.c,%.o,$(wildcard *.c))
AS_OBJS = $(patsubst %.asm,%.o,$(wildcard *.asm))
ALL_OBJS = $(filter-out example.o,$(C_OBJS) $(AS_OBJS) vendor/unity.o)

CC_CMD = $(CC) $(ALL_CFLAGS) -c -o $@ $<

all: tests
@./$<

tests: $(ALL_OBJS)
@$(CC) $(ALL_CFLAGS) $(ALL_LDFLAGS) -o $@ $(ALL_OBJS)

%.o: %.asm
@$(AS) $(ALL_ASFLAGS) -o $@ $<

%.o: %.c
@$(CC_CMD)

vendor/unity.o: vendor/unity.c vendor/unity.h vendor/unity_internals.h
@$(CC_CMD)

clean:
@rm -f *.o vendor/*.o tests

.PHONY: all clean
11 changes: 11 additions & 0 deletions exercises/practice/knapsack/knapsack.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
section .text
global maximumValue

maximumValue:
; Provide your implementation here
ret

%ifidn __OUTPUT_FORMAT__,elf64
section .note.GNU-stack noalloc noexec nowrite progbits
%endif

115 changes: 115 additions & 0 deletions exercises/practice/knapsack/knapsack_test.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Version: 0

#include "stdint.h"
#include "vendor/unity.h"

typedef struct {
uint32_t value;
uint32_t weight;
} Item;

#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

extern uint32_t maximumValue(Item *items, uint32_t count, uint32_t maxWeight);

void setUp(void) {
}

void tearDown(void) {
}

void test_no_items(void) {
TEST_ASSERT_EQUAL_UINT32(0, maximumValue(NULL, 0, 100));
}

void test_one_item_too_heavy(void) {
TEST_IGNORE();
Item items[1] = {
{1, 100}
};
TEST_ASSERT_EQUAL_UINT32(0, maximumValue(items, ARRAY_SIZE(items), 10));
}

void test_five_items_cannot_be_greedy_by_weight(void) {
TEST_IGNORE();
Item items[5] = {
{5, 2},
{5, 2},
{5, 2},
{5, 2},
{21, 10}
};
TEST_ASSERT_EQUAL_UINT32(21, maximumValue(items, ARRAY_SIZE(items), 10));
}

void test_five_items_cannot_be_greedy_by_value(void) {
TEST_IGNORE();
Item items[5] = {
{20, 2},
{20, 2},
{20, 2},
{20, 2},
{50, 10}
};
TEST_ASSERT_EQUAL_UINT32(80, maximumValue(items, ARRAY_SIZE(items), 10));
}

void test_example_knapsack(void) {
TEST_IGNORE();
Item items[4] = {
{10, 5},
{40, 4},
{30, 6},
{50, 4}
};
TEST_ASSERT_EQUAL_UINT32(90, maximumValue(items, ARRAY_SIZE(items), 10));
}

void test_8_items(void) {
TEST_IGNORE();
Item items[8] = {
{350, 25},
{400, 35},
{450, 45},
{20, 5},
{70, 25},
{8, 3},
{5, 2},
{5, 2}
};
TEST_ASSERT_EQUAL_UINT32(900, maximumValue(items, ARRAY_SIZE(items), 104));
}

void test_15_items(void) {
TEST_IGNORE();
Item items[15] = {
{135, 70},
{139, 73},
{149, 77},
{150, 80},
{156, 82},
{163, 87},
{173, 90},
{184, 94},
{192, 98},
{201, 106},
{210, 110},
{214, 113},
{221, 115},
{229, 118},
{240, 120}
};
TEST_ASSERT_EQUAL_UINT32(1458, maximumValue(items, ARRAY_SIZE(items), 750));
}

int main(void) {
UNITY_BEGIN();
RUN_TEST(test_no_items);
RUN_TEST(test_one_item_too_heavy);
RUN_TEST(test_five_items_cannot_be_greedy_by_weight);
RUN_TEST(test_five_items_cannot_be_greedy_by_value);
RUN_TEST(test_example_knapsack);
RUN_TEST(test_8_items);
RUN_TEST(test_15_items);
return UNITY_END();
}
Loading