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 #2263

Merged
merged 1 commit into from
May 4, 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
14 changes: 14 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2634,6 +2634,20 @@
"bit-manipulation"
],
"difficulty": 3
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "677c9cf8-d94c-423c-aba1-45ff19805655",
"practices": [
"tuples"
],
"prerequisites": [
"numbers",
"arrays",
"tuples"
],
"difficulty": 5
}
],
"foregone": [
Expand Down
6 changes: 6 additions & 0 deletions exercises/Exercises.sln
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,7 @@ EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LogAnalysis", "concept\log-analysis\LogAnalysis.csproj", "{D66F4A88-0765-4D6B-A8A4-933E5882EC92}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EliudsEggs", "practice\eliuds-eggs\EliudsEggs.csproj", "{2F3B7384-F4CA-4925-B07C-E05DB3FAC01B}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Knapsack", "practice\knapsack\Knapsack.csproj", "{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -1027,6 +1028,10 @@ Global
{2F3B7384-F4CA-4925-B07C-E05DB3FAC01B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2F3B7384-F4CA-4925-B07C-E05DB3FAC01B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2F3B7384-F4CA-4925-B07C-E05DB3FAC01B}.Release|Any CPU.Build.0 = Release|Any CPU
{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down Expand Up @@ -1201,6 +1206,7 @@ Global
{82C5DF7B-6F86-40D3-8F65-4B63D41E23A5} = {E276EF69-669A-43E0-88AC-8ABB17A9C026}
{D66F4A88-0765-4D6B-A8A4-933E5882EC92} = {3303F74B-62AC-47B7-A8AA-F93A52A1C95C}
{2F3B7384-F4CA-4925-B07C-E05DB3FAC01B} = {E276EF69-669A-43E0-88AC-8ABB17A9C026}
{90C70CAA-A225-4D66-8B42-6AC82AD1D5DC} = {E276EF69-669A-43E0-88AC-8ABB17A9C026}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {AB4EA6C9-5461-4024-BDC7-2AE0C3A85CD1}
Expand Down
35 changes: 35 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Instructions

In this exercise, let's try to solve a classic problem.

Bob is a thief.
After months of careful planning, he finally manages to crack the security systems of a high-class apartment.

In front of him are many items, each with a value (v) and weight (w).
Bob, of course, wants to maximize the total value he can get; he would gladly take all of the items if he could.
However, to his horror, he realizes that the knapsack he carries with him can only hold so much weight (W).

Given a knapsack with a specific carrying capacity (W), help Bob determine the maximum value he can get from the items in the house.
Note that Bob can take only one of each item.

All values given will be strictly positive.
Items will be represented as a list of items.
Each item will have a weight and value.

For example:

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

Knapsack Limit: 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.
141 changes: 141 additions & 0 deletions exercises/practice/knapsack/.editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
###############################
# Core EditorConfig Options #
###############################

; This file is for unifying the coding style for different editors and IDEs.
; More information at:
; https://docs.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017
; https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017

root = true

[*]
indent_style = space

[Knapsack.cs]
indent_size = 4

###############################
# .NET Coding Conventions #
###############################

# Organize usings
dotnet_sort_system_directives_first = true
dotnet_separate_import_directive_groups = true

# this. preferences
dotnet_style_qualification_for_field = false:suggestion
dotnet_style_qualification_for_property = false:suggestion
dotnet_style_qualification_for_method = false:suggestion
dotnet_style_qualification_for_event = false:suggestion

# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion

# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:suggestion

# Modifier preferences
dotnet_style_require_accessibility_modifiers = always:suggestion
dotnet_style_readonly_field = true:suggestion

# Expression-level preferences
dotnet_style_object_initializer = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_auto_properties = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion
dotnet_style_prefer_conditional_expression_over_return = true:suggestion
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion

###############################
# Naming Conventions #
###############################

# Style Definitions
dotnet_naming_style.pascal_case_style.capitalization = pascal_case

# Use PascalCase for constant fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
dotnet_naming_symbols.constant_fields.applicable_kinds = field
dotnet_naming_symbols.constant_fields.applicable_accessibilities = *
dotnet_naming_symbols.constant_fields.required_modifiers = const

###############################
# C# Code Style Rules #
###############################

# var preferences
csharp_style_var_for_built_in_types = true:none
csharp_style_var_when_type_is_apparent = true:none
csharp_style_var_elsewhere = true:none

# Expression-bodied members
csharp_style_expression_bodied_methods = true:suggestion
csharp_style_expression_bodied_constructors = true:suggestion
csharp_style_expression_bodied_operators = true:suggestion
csharp_style_expression_bodied_properties = true:suggestion
csharp_style_expression_bodied_indexers = true:suggestion
csharp_style_expression_bodied_accessors = true:suggestion

# Pattern-matching preferences
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion

# Null-checking preferences
csharp_style_throw_expression = true:suggestion
csharp_style_conditional_delegate_call = true:suggestion

# Modifier preferences
csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion

# Expression-level preferences
csharp_prefer_braces = true:none
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion

###############################
# C# Formatting Rules #
###############################

# New line preferences
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = false
csharp_new_line_before_members_in_anonymous_types = false
csharp_new_line_between_query_expression_clauses = true

# Indentation preferences
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_indent_labels = flush_left

# Space preferences
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_around_binary_operators = before_and_after
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false

# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
22 changes: 22 additions & 0 deletions exercises/practice/knapsack/.meta/Example.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public static class Knapsack
{
public static int MaximumValue(int maximumWeight, (int weight, int value)[] items)
{
var maxWeightForSize = new int[items.Length + 1, maximumWeight + 1];

for (var item = 1; item <= items.Length; item++)
{
for (var capacity = 1; capacity <= maximumWeight; capacity++)
{
var maxWithCurrent =
capacity >= items[item - 1].weight
? maxWeightForSize[item - 1, capacity - items[item - 1].weight] + items[item - 1].value
: 0;

maxWeightForSize[item, capacity] = Math.Max(maxWeightForSize[item - 1, capacity], maxWithCurrent);
}
}

return maxWeightForSize[items.Length, maximumWeight];
}
}
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": [
"erikschierboom"
],
"files": {
"solution": [
"Knapsack.cs"
],
"test": [
"KnapsackTests.cs"
],
"example": [
".meta/Example.cs"
]
},
"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"
}
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"
7 changes: 7 additions & 0 deletions exercises/practice/knapsack/Knapsack.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
public static class Knapsack
{
public static int MaximumValue(int maximumWeight, (int weight, int value)[] items)
{
throw new System.NotImplementedException("You need to implement this method.");
}
}
26 changes: 26 additions & 0 deletions exercises/practice/knapsack/Knapsack.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Exercism.Tests" Version="0.1.0-beta1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.8.3" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

</Project>
58 changes: 58 additions & 0 deletions exercises/practice/knapsack/KnapsackTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Xunit;

public class KnapsackTests
{
[Fact]
public void No_items()
{
Assert.Equal(0, Knapsack.MaximumValue(100, []));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void One_item_too_heavy()
{
(int weight, int value)[] items = [(weight: 100, value: 1)];
Assert.Equal(0, Knapsack.MaximumValue(10, items));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void Five_items_cannot_be_greedy_by_weight_()
{
(int weight, int value)[] items = [(weight: 2, value: 5), (weight: 2, value: 5), (weight: 2, value: 5), (weight: 2, value: 5), (weight: 10, value: 21)];
Assert.Equal(21, Knapsack.MaximumValue(10, items));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void Five_items_cannot_be_greedy_by_value_()
{
(int weight, int value)[] items = [(weight: 2, value: 20), (weight: 2, value: 20), (weight: 2, value: 20), (weight: 2, value: 20), (weight: 10, value: 50)];
Assert.Equal(80, Knapsack.MaximumValue(10, items));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void Example_knapsack()
{
(int weight, int value)[] items = [(weight: 5, value: 10), (weight: 4, value: 40), (weight: 6, value: 30), (weight: 4, value: 50)];
Assert.Equal(90, Knapsack.MaximumValue(10, items));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void Number_8_items()
{
(int weight, int value)[] items = [(weight: 25, value: 350), (weight: 35, value: 400), (weight: 45, value: 450), (weight: 5, value: 20), (weight: 25, value: 70), (weight: 3, value: 8), (weight: 2, value: 5), (weight: 2, value: 5)];
Assert.Equal(900, Knapsack.MaximumValue(104, items));
}

[Fact(Skip = "Remove this Skip property to run this test")]
public void Number_15_items()
{
(int weight, int value)[] items = [
(weight: 70, value: 135), (weight: 73, value: 139), (weight: 77, value: 149), (weight: 80, value: 150),
(weight: 82, value: 156), (weight: 87, value: 163), (weight: 90, value: 173), (weight: 94, value: 184),
(weight: 98, value: 192), (weight: 106, value: 201), (weight: 110, value: 210),
(weight: 113, value: 214), (weight: 115, value: 221), (weight: 118, value: 229),
(weight: 120, value: 240)
];
Assert.Equal(1458, Knapsack.MaximumValue(750, items));
}
}
Loading
Loading