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

1 new exercise: knapsack #151

Merged
merged 1 commit into from
Jun 6, 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 @@ -369,6 +369,14 @@
"prerequisites": [],
"difficulty": 3
},
{
"slug": "knapsack",
"name": "Knapsack",
"uuid": "0408328a-3e04-4e2a-b5bf-fad131747a09",
"practices": [],
"prerequisites": [],
"difficulty": 3
},
{
"slug": "meetup",
"name": "Meetup",
Expand Down
37 changes: 37 additions & 0 deletions exercises/practice/knapsack/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# 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 pairs, `wi` and `vi`, where the first element `wi` is the weight of
the *i*th item and `vi` is the value for that item.

For example:

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.
26 changes: 26 additions & 0 deletions exercises/practice/knapsack/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"authors": [
"kapitaali"
],
"files": {
"solution": [
"src/knapsack.cob"
],
"test": [
"tst/knapsack/knapsack.cut"
],
"example": [
".meta/proof.ci.cob"
],
"invalidator": [
"test.ps1",
"test.sh",
"bin/fetch-cobolcheck",
"bin/fetch-cobolcheck.ps1",
"config.properties"
]
},
"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"
}
85 changes: 85 additions & 0 deletions exercises/practice/knapsack/.meta/proof.ci.cob
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
IDENTIFICATION DIVISION.
PROGRAM-ID. KNAPSACK.
AUTHOR. kapitaali.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
REPOSITORY.
FUNCTION ALL INTRINSIC.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-INPUTS.
05 MAXIMUM-WEIGHT PIC 999.
05 NO-OF-ITEMS PIC 99.

01 KNAPSACKTABLE.
05 TABLEROW OCCURS 1 TO 20 DEPENDING ON NO-OF-ITEMS
INDEXED BY INDX.
10 WS-WEIGHT PIC 9999.
10 WS-VALUE PIC 9999.

01 WS-OUTPUTS.
05 WS-RESULT PIC 9999.

01 MY-VARS.
05 A PIC 9999.
05 B PIC 9999.
05 C PIC 9999.
05 I PIC 9999.
05 J PIC 9999.
05 ITEMS-PLUS1 PIC 9999.
05 WEIGHT-PLUS1 PIC 9999.

01 MY-TABLE.
05 W OCCURS 1 TO 9999 DEPENDING ON MAXIMUM-WEIGHT.
10 ITEMS OCCURS 20 TIMES.
15 M PIC 9999.


PROCEDURE DIVISION.


INIT-MY-TABLE.
IF MAXIMUM-WEIGHT = 0
MOVE 1 TO MAXIMUM-WEIGHT
INITIALIZE MY-TABLE
MOVE 0 TO MAXIMUM-WEIGHT
ELSE
INITIALIZE MY-TABLE
END-IF.


MAXIMUM-VALUE.
PERFORM INIT-MY-TABLE.
MOVE ZEROES TO MY-TABLE.
MOVE ZEROES TO MY-VARS.
INITIALIZE WS-RESULT.
SET INDX TO NO-OF-ITEMS.
IF NO-OF-ITEMS = 1
IF WS-WEIGHT(1) > MAXIMUM-WEIGHT
EXIT PROGRAM
END-IF
END-IF.
SORT TABLEROW DESCENDING WS-VALUE WS-WEIGHT.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > NO-OF-ITEMS
PERFORM VARYING J FROM 1 BY 1 UNTIL J > MAXIMUM-WEIGHT
IF WS-WEIGHT(I) > J THEN
COMPUTE C = I - 1
IF C = 0
MOVE 0 TO M(J,I)
ELSE
MOVE M(J, C) TO M(J,I)
END-IF
ELSE
COMPUTE B = J - WS-WEIGHT(I)
IF C > 0 AND B > 0
COMPUTE A = WS-VALUE(I) + M(B, C)
COMPUTE M(J,I) = MAX(M(J, C), A)
ELSE
COMPUTE A = WS-VALUE(I)
COMPUTE M(J,I) = MAX(0, A)
END-IF
END-IF
END-PERFORM
END-PERFORM.
MOVE M(MAXIMUM-WEIGHT, NO-OF-ITEMS) TO WS-RESULT.
63 changes: 63 additions & 0 deletions exercises/practice/knapsack/bin/fetch-cobolcheck
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#!/usr/bin/env bash

# This file is a copy of the
# https://github.com/exercism/configlet/blob/main/scripts/fetch-configlet file.
# Please submit bugfixes/improvements to the above file to ensure that all tracks benefit from the changes.

# set -eo pipefail

readonly LATEST='https://api.github.com/repos/0xE282B0/cobol-check/releases/latest'

case "$(uname)" in
Darwin*) os='mac' ;;
Linux*) os='linux' ;;
Windows*) os='windows' ;;
MINGW*) os='windows' ;;
MSYS_NT-*) os='windows' ;;
*) os='linux' ;;
esac

case "${os}" in
windows*) ext='.exe' ;;
*) ext='' ;;
esac

arch="$(uname -m)"

curlopts=(
--silent
--show-error
--fail
--location
--retry 3
)

if [[ -n "${GITHUB_TOKEN}" ]]; then
curlopts+=(--header "authorization: Bearer ${GITHUB_TOKEN}")
fi

suffix="${os}-${arch}${ext}"

get_download_url() {
curl "${curlopts[@]}" --header 'Accept: application/vnd.github.v3+json' "${LATEST}" |
grep "\"browser_download_url\": \".*/download/.*/cobol-check.*${suffix}\"$" |
cut -d'"' -f4
}

main() {
if [[ -d ./bin ]]; then
output_dir="./bin"
elif [[ $PWD == */bin ]]; then
output_dir="$PWD"
else
echo "Error: no ./bin directory found. This script should be ran from a repo root." >&2
return 1
fi

output_path="${output_dir}/cobolcheck${ext}"
download_url="$(get_download_url)"
curl "${curlopts[@]}" --output "${output_path}" "${download_url}"
chmod +x "${output_path}"
}

main
28 changes: 28 additions & 0 deletions exercises/practice/knapsack/bin/fetch-cobolcheck.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# This file is a copy of the
# https://github.com/exercism/configlet/blob/main/scripts/fetch-configlet.ps1 file.
# Please submit bugfixes/improvements to the above file to ensure that all tracks
# benefit from the changes.

$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"

$requestOpts = @{
Headers = If ($env:GITHUB_TOKEN) { @{ Authorization = "Bearer ${env:GITHUB_TOKEN}" } } Else { @{ } }
MaximumRetryCount = 3
RetryIntervalSec = 1
}

$arch = If ([Environment]::Is64BitOperatingSystem) { "amd64" } Else { "x86" }
$fileName = "cobol-check-windows-$arch.exe"

Function Get-DownloadUrl {
$latestUrl = "https://api.github.com/repos/0xE282B0/cobol-check/releases/latest"
Invoke-RestMethod -Uri $latestUrl -PreserveAuthorizationOnRedirect @requestOpts
| Select-Object -ExpandProperty assets
| Where-Object { $_.browser_download_url -match $FileName }
| Select-Object -ExpandProperty browser_download_url
}

$downloadUrl = Get-DownloadUrl
$outputFile = Join-Path -Path $PSScriptRoot -ChildPath "cobolcheck.exe"
Invoke-WebRequest -Uri $downloadUrl -OutFile $outputFile @requestOpts
Loading
Loading