Knapsack problem/0-1: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 92:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F totalvalue(comb)
V totwt = 0
V totval = 0
Line 133:
print("Bagged the following items\n "sorted(bagged.map((item, _, _2) -> item)).join("\n "))
V (val, wt) = totalvalue(bagged)
print(‘for a total value of #. and a total weight of #.’.format(val, -wt))</langsyntaxhighlight>
 
{{out}}
Line 155:
=={{header|360 Assembly}}==
Non recurvive brute force version.
<langsyntaxhighlight lang="360asm">* Knapsack problem/0-1 16/02/2017
KNAPSA01 CSECT
USING KNAPSA01,R13
Line 278:
DATAE DC 0C
YREGS
END KNAPSA01</langsyntaxhighlight>
{{out}}
<pre>
Line 298:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Ada.Strings.Unbounded;
 
Line 406:
end if;
end loop;
end Knapsack_01;</langsyntaxhighlight>
{{out}}
<pre>
Line 427:
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl"> ∇ ret←NapSack;sum;b;list;total
[1] total←400
[2] list←("map" 9 150)("compass" 13 35)("water" 153 200)("sandwich" 50 160)("glucose" 15 60) ("tin" 68 45)("banana" 27 60)("apple" 39 40)("cheese" 23 30)("beer" 52 10) ("suntan cream" 11 70)("camera" 32 30)("t-shirt" 24 15)("trousers" 48 10) ("umbrella" 73 40)("waterproof trousers" 42 70)("waterproof overclothes" 43 75) ("note-case" 22 80) ("sunglasses" 7 20) ("towel" 18 12) ("socks" 4 50) ("book" 30 10)
Line 439:
[10] :end
[11] ret←⊃ret,⊂'TOTALS:' (+/2⊃¨ret)(+/3⊃¨ret)
∇</langsyntaxhighlight>
{{out}}
<pre>
Line 461:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KNAPSACK_PROBLEM_0-1.AWK
BEGIN {
Line 505:
exit(0)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 528:
{{works with|QuickBasic|4.5}}
{{trans|QB64}}
<langsyntaxhighlight lang="qbasic">N = 7: G = 5: a = 2 ^ (N + 1) ' Author: DANILIN & Editor: Jjuanhdez or Unknow
RANDOMIZE TIMER
DIM L(N), C(N), j(N), q(a), d(a), q$(a)
Line 563:
IF d(i) <= G AND q(i) > max THEN max = q(i): h = i
NEXT i
PRINT d(h), q(h), q$(h)</langsyntaxhighlight>
{{out}}
<pre>Same as QB64 entry.</pre>
Line 569:
==={{header|Yabasic}}===
{{trans|QB64}}
<langsyntaxhighlight lang="freebasic">N = 7 : G = 5 : a = 2^(N+1) ' Author: DANILIN & Editor: Jjuanhdez or Unknow
dim L(N), C(N), j(N), q(a), d(a), q$(a)
 
Line 604:
next i
print d(h), chr$(9), q(h), chr$(9), q$(h)
end</langsyntaxhighlight>
{{out}}
<pre>Same as QB64 entry
Line 610:
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
:: Initiate command line environment
@echo off
Line 677:
echo Total Value: %totalimportance% Total Weight: %totalweight%
pause>nul
</syntaxhighlight>
</lang>
 
{{out}}
Line 687:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> HIMEM = PAGE + 8000000
nItems% = 22
maxWeight% = 400
Line 751:
m{(index%)} = excluded{}
ENDIF
= index%</langsyntaxhighlight>
{{out}}
<pre>
Line 772:
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(knapsack=
( things
= (map.9.150)
Line 837:
& out$(!maxvalue.!sack));
!knapsack;</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="bracmat"> 1030
. map
compass
Line 851:
note-case
sunglasses
socks</langsyntaxhighlight>
 
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 933:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 954:
{{libheader|System}}
{{libheader|System.Collections.Generic}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,095:
}
}
}</langsyntaxhighlight>
("Bag" might not be the best name for the class, since "bag" is sometimes also used to refer to a multiset data structure.)
 
Line 1,109:
Random values origin are automatically assigned create integral of quantity and quality
 
<langsyntaxhighlight lang="csharp">using System; // Knapsack C# binary DANILIN
using System.Text; // rextester.com/YRFA61366
namespace Knapsack
Line 1,180:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,212:
=== First version ===
{{libheader|Boost}}
<langsyntaxhighlight lang="cpp">#include <vector>
#include <string>
#include <iostream>
Line 1,309:
bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;
return bestValues[ n - 1 ][ weightlimit - 1 ] ;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,331:
=== Second version ===
{{Works with|C++17}}
<langsyntaxhighlight lang="cpp">#include <iomanip>
#include <iostream>
#include <set>
Line 1,406:
std::cout << std::endl << std::setw(24) << "total:" << std::setw(6) << totalweight << std::setw(6) << bestValue << std::endl;
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre> best knapsack:
Line 1,426:
=={{header|C_sharp}}==
All combinations, eight threads, break when weight is to large.
<langsyntaxhighlight lang="csharp">using System; // 4790@3.6
using System.Threading.Tasks;
class Program
Line 1,476:
"waterproof trousers","waterproof overclothes",
"note-case","sunglasses","towel","socks","book"};
}</langsyntaxhighlight>
A dynamic version.
<langsyntaxhighlight lang="csharp">using System
class program
{
Line 1,521:
"waterproof trousers","waterproof overclothes",
"note-case","sunglasses","towel","socks","book"};
}</langsyntaxhighlight>
 
=={{header|Ceylon}}==
Line 1,528:
<b>module.ceylon</b>:
 
<langsyntaxhighlight lang="ceylon">
module knapsack "1.0.0" {
}
</syntaxhighlight>
</lang>
 
<b>run.ceylon:</b>
 
<langsyntaxhighlight lang="ceylon">
shared void run() {
value knapsack = pack(items, empty(400));
Line 1,618:
then packRecursive(sortedItems.rest, add(firstItem,knapsack))
else knapsack;
</syntaxhighlight>
</lang>
 
 
Line 1,644:
Uses the dynamic programming solution from [[wp:Knapsack_problem#0-1_knapsack_problem|Wikipedia]].
First define the ''items'' data:
<langsyntaxhighlight lang="clojure">(def item-data
[ "map" 9 150
"compass" 13 35
Line 1,670:
(defstruct item :name :weight :value)
 
(def items (vec (map #(apply struct item %) (partition 3 item-data))))</langsyntaxhighlight>
''m'' is as per the Wikipedia formula, except that it returns a pair ''[value indexes]'' where ''indexes'' is a vector of index values in ''items''. ''value'' is the maximum value attainable using items 0..''i'' whose total weight doesn't exceed ''w''; ''indexes'' are the item indexes that produces the value.
<langsyntaxhighlight lang="clojure">(declare mm) ;forward decl for memoization function
 
(defn m [i w]
Line 1,688:
no))))))
 
(def mm (memoize m))</langsyntaxhighlight>
Call ''m'' and print the result:
<langsyntaxhighlight lang="clojure">(use '[clojure.string :only [join]])
 
(let [[value indexes] (m (-> items count dec) 400)
Line 1,696:
(println "items to pack:" (join ", " names))
(println "total value:" value)
(println "total weight:" (reduce + (map (comp :weight items) indexes))))</langsyntaxhighlight>
{{out}}
<pre>items to pack: map, compass, water, sandwich, glucose, banana, suntan cream, waterproof trousers,
Line 1,705:
=={{header|Common Lisp}}==
Cached method.
<langsyntaxhighlight lang="lisp">;;; memoize
(defmacro mm-set (p v) `(if ,p ,p (setf ,p ,v)))
 
Line 1,734:
(T-shirt 24 15) (trousers 48 10) (umbrella 73 40)
(trousers 42 70) (overclothes 43 75) (notecase 22 80)
(glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10))))</langsyntaxhighlight>
{{out}}
<pre>(1030 396
Line 1,743:
=={{header|Crystal}}==
Branch and bound solution
<langsyntaxhighlight Rubylang="ruby">require "bit_array"
 
struct BitArray
Line 1,829:
puts "total weight #{used.sum(&.weight)}, total value #{used.sum(&.value)}"
puts "checked nodes: #{solver.checked_nodes}"
</syntaxhighlight>
</lang>
{{out}}
<pre>optimal choice: ["map", "socks", "suntan cream", "glucose", "note-case", "sandwich", "sunglasses", "compass", "banana", "waterproof overclothes", "waterproof trousers", "water"]
Line 1,838:
===Dynamic Programming Version===
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.array, std.range;
 
struct Item { string name; int weight, value; }
Line 1,882:
const t = reduce!q{ a[] += [b.weight, b.value] }([0, 0], bag);
writeln("\nTotal weight and value: ", t[0] <= limit ? t : [0, 0]);
}</langsyntaxhighlight>
{{out}}
<pre>Items:
Line 1,902:
===Brute Force Version===
{{trans|C}}
<langsyntaxhighlight lang="d">struct Item { string name; int weight, value; }
 
immutable Item[] items = [
Line 1,957:
}
writefln("\nTotal value: %d; weight: %d", s.value, w);
}</langsyntaxhighlight>
The runtime is about 0.09 seconds.
{{out}}
Line 1,978:
===Short Dynamic Programming Version===
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.array, std.range;
 
struct Item { string name; int w, v; }
Line 1,999:
void main() {
reduce!addItem(Pair().repeat.take(400).array, items).back.writeln;
}</langsyntaxhighlight>
Runtime about 0.04 seconds.
{{out}}
Line 2,005:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">List solveKnapsack(items, maxWeight) {
int MIN_VALUE=-100;
int N = items.length; // number of items
Line 2,108:
print("Elapsed Time = ${sw.elapsedInMs()}ms");
}</langsyntaxhighlight>
{{out}}
<pre>[item, profit, weight]
Line 2,128:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">name$[] = [ "map" "compass" "water" "sandwich" "glucose" "tin" "banana" "apple" "cheese" "beer" "suntan cream" "camera" "t-shirt" "trousers" "umbrella" "waterproof trousers" "waterproof overclothes" "note-case" "sunglasses" "towel" "socks" "book" ]
weight[] = [ 9 13 153 50 15 68 27 39 23 52 11 32 24 48 73 42 43 22 7 18 4 30 ]
value[] = [ 150 35 200 160 60 45 60 40 30 10 70 30 15 10 40 70 75 80 20 12 50 10 ]
Line 2,158:
for i range len items[]
print " " & name$[items[i]]
.</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(require 'struct)
(require 'hash)
Line 2,196:
(set! restant (- restant (poids i)))
(name i)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
;; init table
(define goodies
Line 2,219:
(length (hash-keys H))
→ 4939 ;; number of entries "i | weight" in hash table
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 2,263:
 
end
</syntaxhighlight>
</lang>
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
ITEM
Line 2,300:
 
end
</syntaxhighlight>
</lang>
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
KNAPSACKZEROONE
Line 2,408:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,429:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Knapsack do
def solve([], _total_weight, item_acc, value_acc, weight_acc), do:
{item_acc, value_acc, weight_acc}
Line 2,489:
IO.puts "Time elapsed in milliseconds: #{time/1000}"
end
go.(stuff, max_weight)</langsyntaxhighlight>
 
{{out}}
Line 2,515:
{{Trans|Common Lisp}} with changes (memoization without macro)
 
<langsyntaxhighlight lang="lisp">
(defun ks (max-w items)
(let ((cache (make-vector (1+ (length items)) nil)))
Line 2,550:
(waterproof-trousers 42 70) (overclothes 43 75) (notecase 22 80)
(glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,560:
 
Another way without cache :
<langsyntaxhighlight lang="lisp">
(defun best-rate (l1 l2)
"predicate for sorting a list of elements regarding the value/weight rate"
Line 2,608:
(waterproof-trousers 42 70) (overclothes 43 75) (notecase 22 80)
(glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10)) 400)
</syntaxhighlight>
</lang>
 
{{out}} with org-babel in Emacs
Line 2,630:
=={{header|Erlang}}==
 
<syntaxhighlight lang="erlang">
<lang Erlang>
 
-module(knapsack_0_1).
Line 2,703:
HeadRes
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,729:
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>items=["map","compass","water","sandwich","glucose", ...
> "tin","banana","apple","cheese","beer","suntan creame", ...
Line 2,756:
sunglasses
socks
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
===Using A* Algorithm===
<langsyntaxhighlight lang="fsharp">
//Solve Knapsack 0-1 using A* algorithm
//Nigel Galloway, August 3rd., 2018
Line 2,783:
if bv>=h then t else fN (fH zl (bv,t) zw zv zt)
fN (fH 0 (0.0,[]) 0.0 0.0 [])
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="fsharp">
let itemsf = [
"map", 9.0, 150.0;
Line 2,809:
"socks", 4.0, 50.0;
"book", 30.0, 10.0;]|> List.sortBy(fun(_,n,g)->n/g)
</syntaxhighlight>
</lang>
<pre>
> let x=knapStar itemsf 400.0;;
Line 2,833:
=={{header|Factor}}==
Using dynamic programming:
<langsyntaxhighlight lang="factor">USING: accessors arrays fry io kernel locals make math
math.order math.parser math.ranges sequences sorting ;
IN: rosetta.knappsack.0-1
Line 2,909:
"Items packed: " print
natural-sort
[ " " write print ] each ;</langsyntaxhighlight>
<pre>
( scratchpad ) main
Line 2,929:
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
<lang Forth>
\ Rosetta Code Knapp-sack 0-1 problem. Tested under GForth 0.7.3.
\ 22 items. On current processors a set fits nicely in one CELL (32 or 64 bits).
Line 3,000:
." Weight: " Sol @ [ END-SACK Sack ]sum . ." Value: " Sol @ [ END-SACK VAL + Sack VAL + ]sum .
;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,020:
=={{header|FreeBASIC}}==
{{trans|XPL0}}
<langsyntaxhighlight lang="freebasic">#define Tabu = Chr(9)
Dim As Integer i, A, P, V, N
Dim As Integer MejorArticulo, MejorValor = 0
Line 3,068:
Wend
Print "Totals:"; Spc(25); P; Tabu; V
Sleep</langsyntaxhighlight>
{{out}}
<pre>Same as XLP0 entry.</pre>
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">window 1, @"Knapsack Problem", (0,0,480,270)
 
_maxWeight = 400
Line 3,145:
fn FillKnapsack
 
HandleEvents</langsyntaxhighlight>
 
{{output}}
Line 3,170:
=={{header|Go}}==
From WP, "0-1 knapsack problem" under [http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_Programming_Algorithm|Solving The Knapsack Problem], although the solution here simply follows the recursive defintion and doesn't even use the array optimization.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,226:
}
return i0, w0, v0
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,236:
 
Data for which a greedy algorithm might give an incorrect result:
<syntaxhighlight lang="go">
<lang go>
var wants = []item{
{"sunscreen", 15, 2},
Line 3,244:
 
const maxWt = 40
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,254:
=={{header|Groovy}}==
Solution #1: brute force
<langsyntaxhighlight lang="groovy">def totalWeight = { list -> list*.weight.sum() }
def totalValue = { list -> list*.value.sum() }
Line 3,262:
350 < w && w < 401
}.max(totalValue)
}</langsyntaxhighlight>
Solution #2: dynamic programming
<langsyntaxhighlight lang="groovy">def knapsack01dp = { possibleItems ->
def n = possibleItems.size()
def m = (0..n).collect{ i -> (0..400).collect{ w -> []} }
Line 3,274:
}
m[n][400]
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def items = [
[name:"map", weight:9, value:150],
[name:"compass", weight:13, value:35],
Line 3,312:
printf (" item: %-25s weight:%4d value:%4d\n", it.name, it.weight, it.value)
}
}</langsyntaxhighlight>
{{out}}
<pre>Elapsed Time: 132.267 s
Line 3,350:
=={{header|Haskell}}==
Brute force:
<langsyntaxhighlight lang="haskell">inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160),
("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40),
("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30),
Line 3,366:
putStr "Total value: "; print value
mapM_ print items
where (value, items) = maximum $ combs inv 400</langsyntaxhighlight>
{{out}}
<pre>
Line 3,384:
</pre>
Much faster brute force solution that computes the maximum before prepending, saving most of the prepends:
<langsyntaxhighlight lang="haskell">inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160),
("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40),
("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30),
Line 3,398:
skipthis = combs rest cap
 
main = do print $ combs inv 400</langsyntaxhighlight>
{{out}}
<pre>(1030,[("map",9,150),("compass",13,35),("water",153,200),("sandwich",50,160),("glucose",15,60),("banana",27,60),("cream",11,70),("trousers",42,70),("overclothes",43,75),("notecase",22,80),("sunglasses",7,20),("socks",4,50)])</pre>
 
Dynamic programming with a list for caching (this can be adapted to bounded problem easily):
<langsyntaxhighlight lang="haskell">inv = [("map",9,150), ("compass",13,35), ("water",153,200), ("sandwich",50,160),
("glucose",15,60), ("tin",68,45), ("banana",27,60), ("apple",39,40),
("cheese",23,30), ("beer",52,10), ("cream",11,70), ("camera",32,30),
Line 3,415:
(left,right) = splitAt w list
 
main = print $ (knapsack inv) !! 400</langsyntaxhighlight>
{{out}}
(1030,["map","compass","water","sandwich","glucose","banana","cream","waterproof trousers","overclothes","notecase","sunglasses","socks"])
Line 3,421:
=={{header|Icon}} and {{header|Unicon}}==
Translation from Wikipedia pseudo-code. Memoization can be enabled with a command line argument that causes the procedure definitions to be swapped which effectively hooks the procedure.
<langsyntaxhighlight Iconlang="icon">link printf
 
global wants # items wanted for knapsack
Line 3,496:
packing(["socks"], 4, 50),
packing(["book"], 30, 10) ]
end</langsyntaxhighlight>
{{libheader|Icon Programming Library}}
[http://www.cs.arizona.edu/icon/library/src/procs/printf.icn printf.icn provides printf]
Line 3,510:
=={{header|J}}==
Static solution:
<langsyntaxhighlight Jlang="j">'names values'=:|:".;._2]0 :0
'map'; 9 150
'compass'; 13 35
Line 3,537:
X=: +/ .*"1
plausible=: (] (] #~ 400 >: X) #:@i.@(2&^)@#)@:({."1)
best=: (plausible ([ {~ [ (i. >./)@:X {:"1@]) ]) values</langsyntaxhighlight>
Illustration of answer:
<langsyntaxhighlight Jlang="j"> +/best#values NB. total weight and value
396 1030
best#names
Line 3,553:
notecase
sunglasses
socks </langsyntaxhighlight>
 
'''Alternative test case'''
 
<langsyntaxhighlight Jlang="j">'names values'=:|:".;._2]0 :0
'sunscreen'; 15 2
'GPS'; 25 2
Line 3,565:
X=: +/ .*"1
plausible=: (] (] #~ 40 >: X) #:@i.@(2&^)@#)@:({."1)
best=: (plausible ([ {~ [ (i. >./)@:X {:"1@]) ]) values</langsyntaxhighlight>
 
Illustration:
 
<langsyntaxhighlight Jlang="j"> +/best#values
40 4
best#names
sunscreen
GPS </langsyntaxhighlight>
 
=={{header|Java}}==
General dynamic solution after [[wp:Knapsack_problem#0-1_knapsack_problem|wikipedia]].
<langsyntaxhighlight lang="java">package hu.pj.alg.test;
 
import hu.pj.alg.ZeroOneKnapsack;
Line 3,660:
}
 
} // class</langsyntaxhighlight>
<langsyntaxhighlight lang="java">package hu.pj.alg;
 
import hu.pj.obj.Item;
Line 3,814:
}
 
} // class</langsyntaxhighlight>
<langsyntaxhighlight lang="java">package hu.pj.obj;
 
public class Item {
Line 3,885:
public int getBounding() {return bounding;}
 
} // class</langsyntaxhighlight>
{{out}}
<pre>
Line 3,909:
=={{header|JavaScript}}==
Also available at [https://gist.github.com/truher/4715551|this gist].
<langsyntaxhighlight lang="javascript">/*global portviz:false, _:false */
/*
* 0-1 knapsack solution, recursive, memoized, approximate.
Line 4,110:
12
]);
});</langsyntaxhighlight>
 
=={{header|jq}}==
Line 4,120:
corresponding to no items). Here, m[i,W] is set to [V, ary]
where ary is an array of the names of the accepted items.
<langsyntaxhighlight lang="jq"># Input should be the array of objects giving name, weight and value.
# Because of the way addition is defined on null and because of the
# way setpath works, there is no need to initialize the matrix m in
Line 4,144:
.[$i][$j] = .[$i-1][$j]
end))
| .[$n][W];</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">def objects: [
{name: "map", "weight": 9, "value": 150},
{name: "compass", "weight": 13, "value": 35},
Line 4,171:
];
 
objects | dynamic_knapsack(400)[]</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$jq -M -c -n -f knapsack.jq
1030
["map","compass","water","sandwich","glucose","banana","suntancream","waterproof trousers","waterproof overclothes","note-case","sunglasses","socks"]</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 4,183:
 
'''Type and Functions''':
<langsyntaxhighlight lang="julia">struct KPDSupply{T<:Integer}
item::String
weight::T
Line 4,199:
sol = mixintprog(-v, w', '<', capacity, :Bin, 0, 1, CbcSolver())
gear[sol.sol .≈ 1]
end</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">gear = [KPDSupply("map", 9, 150),
KPDSupply("compass", 13, 35),
KPDSupply("water", 153, 200),
Line 4,228:
println("The hicker should pack: \n - ", join(pack, "\n - "))
println("\nPacked weight: ", mapreduce(x -> x.weight, +, pack), " kg")
println("Packed value: ", mapreduce(x -> x.value, +, pack), " €")</langsyntaxhighlight>
 
{{out}}
Line 4,250:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
data class Item(val name: String, val weight: Int, val value: Int)
Line 4,303:
println("---------------------- ------ -----")
println("Total ${chosenItems.size} Items Chosen $totalWeight $totalValue")
}</langsyntaxhighlight>
 
{{out}}
Line 4,327:
=={{header|LSL}}==
To test it yourself, rez a box on the ground, add the following as a New Script, create a notecard named "Knapsack_Problem_0_1_Data.txt" with the data shown below.
<langsyntaxhighlight LSLlang="lsl">string sNOTECARD = "Knapsack_Problem_0_1_Data.txt";
integer iMAX_WEIGHT = 400;
integer iSTRIDE = 4;
Line 4,376:
}
}
}</langsyntaxhighlight>
Notecard:
<pre>map, 9, 150
Line 4,419:
=={{Header|Lua}}==
This version is adapted from the Clojure version.
<langsyntaxhighlight lang="lua">items = {
{"map", 9, 150},
{"compass", 13, 35},
Line 4,504:
for k,v in pairs(memo) do count = count + 1 end
printf("\n(memo count: %d; mm call count: %d)", count, mm_calls)
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,514:
</pre>
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">weights := [9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30]:
vals := [150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10]:
items := ["map","compass","water","sandwich","glucose","tin","banana","apple","cheese","beer","suntan cream","camera","T-shirt","trousers","umbrella","waterproof trousers","waterproof overclothes","note-case","sunglasses","towel","socks","book"]:
Line 4,542:
end if:
end do:
printf("Total Weight is %d\n", count):</langsyntaxhighlight>
{{Out}}
<pre>Total Value is 1030
Line 4,561:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Used the
<langsyntaxhighlight lang="mathematica">#[[Flatten@
Position[LinearProgramming[-#[[;; , 3]], -{#[[;; , 2]]}, -{400},
{0, 1} & /@ #, Integers], 1], 1]] &@
Line 4,585:
{"towel", 18, 12},
{"socks", 4, 50},
{"book", 30, 10}}</langsyntaxhighlight>
{{Out}}
<pre>{"map", "compass", "water", "sandwich", "glucose", "banana", "suntan cream", "waterproof trousers", "waterproof overclothes", "note-case", "sunglasses", "socks"}</pre>
 
=={{header|Mathprog}}==
<langsyntaxhighlight lang="mathprog">/*Knapsack
This model finds the integer optimal packing of a knapsack
Line 4,635:
;
 
end;</langsyntaxhighlight>
The solution may be found at [[Knapsack problem/0-1/Mathprog]].
Activity=1 means take, Activity=0 means don't take.
 
=={{header|MAXScript}}==
<syntaxhighlight lang="maxscript">
<lang MAXScript>
global globalItems = #()
global usedMass = 0
Line 4,704:
)
format "Total mass: %, Total Value: %\n" usedMass totalValue
</syntaxhighlight>
</lang>
{{out}}
<syntaxhighlight lang="maxscript">
<lang MAXScript>
Item name: water, weight: 153, value:200
Item name: sandwich, weight: 50, value:160
Line 4,722:
Total mass: 396, Total Value: 1030
OK
</syntaxhighlight>
</lang>
 
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
<lang MiniZinc>
%Knapsack 0/1. Nigel Galloway: October 5th., 2020.
enum Items={map,compass,water,sandwich,glucose,tin,banana,apple,cheese,beer,suntan_cream,camera,t_shirt,trousers,umbrella,waterproof_trousers,waterproof_overclothes,note_case,sunglasses,towel,socks,book};
Line 4,737:
solve maximize wValue;
output["Take "++show(take)++"\nTotal Weight=\(wTaken) Total Value=\(wValue)"]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,749:
:– use a cache for memoization.
 
<syntaxhighlight lang="nim">
<lang Nim>
# Knapsack. Recursive algorithm.
 
Line 4,832:
echo "Total weight: ", weight
echo "Total value: ", value
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,856:
=={{header|OCaml}}==
A brute force solution:
<langsyntaxhighlight lang="ocaml">let items = [
"map", 9, 150;
"compass", 13, 35;
Line 4,896:
(List.hd poss) (List.tl poss) in
List.iter (fun (name,_,_) -> print_endline name) res;
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
Using constraint programming.
<langsyntaxhighlight lang="oz">declare
%% maps items to pairs of Weight(hectogram) and Value
Problem = knapsack('map':9#150
Line 4,963:
{System.printInfo "\n"}
{System.showInfo "total value: "#{Value Best}}
{System.showInfo "total weight: "#{Weight Best}}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,987:
=={{header|Pascal}}==
Uses a stringlist to store the items. I used the algorithm given on Wikipedia (Knapsack problem) to find the maximum value. It is written in pseudocode that translates very easily to Pascal.
<langsyntaxhighlight lang="pascal">
program project1;
uses
Line 5,071:
readln;
end.
</syntaxhighlight>
</lang>
 
Output
Line 5,096:
=={{header|Perl}}==
The dynamic programming solution from Wikipedia.
<langsyntaxhighlight lang="perl">my $raw = <<'TABLE';
map 9 150
compass 13 35
Line 5,154:
 
my $solution = optimal($#name, $max_weight);
print "$solution->[0]: @{$solution->[1]}\n";</langsyntaxhighlight>
{{out}}
<pre>1030: map compass water sandwich glucose banana suntancream waterproof trousers waterproof overclothes note-case sunglasses socks</pre>
Line 5,160:
=={{header|Phix}}==
Trivial simplification of the [[Knapsack_problem/Bounded#Phix|Knapsack/Bounded]] solution. By careful ordering we can ensure we find the optimal solution first (see terminate flag).
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\knapsack0.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 5,233:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 5,256:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">#########################################################
# 0-1 Knapsack Problem Solve with memoization optimize and index returns
# $w = weight of item
Line 5,355:
}
echo "<tr><td align=right><b>Totals</b></td><td>$totalVal</td><td>$totalWt</td></tr>";
echo "</table><hr>";</langsyntaxhighlight>
{{out}}
<div class="solutionoutput">
Line 5,361:
</div>
Minimal PHP Algorithm for totals only translated from Python version as discussed in the YouTube posted video at: http://www.youtube.com/watch?v=ZKBUu_ahSR4
<langsyntaxhighlight lang="php">#########################################################
# 0-1 Knapsack Problem Solve
# $w = weight of item
Line 5,454:
$m3 = knapSolve($w3, $v3, sizeof($v3) -1, 54 );
print_r($w3); echo "<br>";
echo "<b>Max: $m3</b> ($numcalls calls)<br><br>";</langsyntaxhighlight>
{{out}}
<pre>
Line 5,465:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">import mip,util.
 
go =>
Line 5,533:
["socks", 4, 50],
["book", 30, 10]],
MaxTotalWeight = 400.</langsyntaxhighlight>
 
{{out}}
Line 5,555:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de *Items
("map" 9 150) ("compass" 13 35)
("water" 153 200) ("sandwich" 50 160)
Line 5,581:
(for I K
(apply tab I (3 -24 6 6) NIL) )
(tab (27 6 6) NIL (sum cadr K) (sum caddr K)) )</langsyntaxhighlight>
{{out}}
<pre>
Line 5,603:
===Using the clpfd library===
{{libheader|clpfd}}
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
 
knapsack :-
Line 5,672:
sformat(W3, A3, [V]),
format('~w~w~w~n', [W1,W2,W3]),
print_results(A1, A2, A3, T, TR, WM, VM).</langsyntaxhighlight>
{{out}}
<pre>
Line 5,693:
{{libheader|simplex}}
Library written by <b>Markus Triska</b>. The problem is solved in about 3 seconds.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(simplex)).
 
knapsack :-
Line 5,770:
W2 is W1 + W,
V2 is V1 + V),
print_results(S, A1, A2, A3, T, TN, W2, V2).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Solution uses memoization.
<langsyntaxhighlight PureBasiclang="purebasic">Structure item
name.s
weight.i ;units are dekagrams (dag)
Line 5,889:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf </langsyntaxhighlight>
{{out}}
<pre>
Line 5,919:
 
Program write results to qb64 directory
<langsyntaxhighlight lang="qbasic">Open "knapsack.txt" For Output As #1
N=7: L=5: a = 2^(N+1): Randomize Timer 'knapsack.bas DANILIN
Dim L(N), C(N), j(N), q(a), q$(a), d(a)
Line 5,942:
If d(i)<=L Then If q(i) > max Then max=q(i): m=i
Next
Print #1,: Print #1, d(m), q(m), q$(m): End</langsyntaxhighlight>
 
Main thing is very brief and clear to even all<br/><br/>
Line 5,970:
=={{header|Python}}==
===Brute force algorithm===
<langsyntaxhighlight lang="python">from itertools import combinations
 
def anycomb(items):
Line 6,000:
'\n '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))</langsyntaxhighlight>
{{out}}
<pre>
Line 6,019:
</pre>
=== Dynamic programming solution ===
<langsyntaxhighlight lang="python">try:
xrange
except:
Line 6,071:
'\n '.join(sorted(item for item,_,_ in bagged)))
val, wt = totalvalue(bagged)
print("for a total value of %i and a total weight of %i" % (val, -wt))</langsyntaxhighlight>
===Recursive dynamic programming algorithm===
<langsyntaxhighlight lang="python">def total_value(items, max_weight):
return sum([x[2] for x in items]) if sum([x[1] for x in items]) <= max_weight else 0
Line 6,108:
print x[0]
print "value:", total_value(solution, max_weight)
print "weight:", sum([x[1] for x in solution])</langsyntaxhighlight>
 
 
Line 6,120:
Random values origin are automatically assigned create integral of quantity and quality
 
<langsyntaxhighlight lang="python">n=5; N=n+1; G=5; a=2**N # KNAPSACK 0-1 DANILIN
L=[];C=[];e=[];j=[];q=[];s=[] # rextester.com/BCKP19591
d=[];L=[1]*n;C=[1]*n;e=[1]*a
Line 6,149:
if d[i]<=G and q[i]>max:
max=q[i]; m=i
print (d[m], q[m], e[m])</langsyntaxhighlight>
{{out}}
<pre># Mass Cost
Line 6,169:
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang r>
Full_Data<-structure(list(item = c("map", "compass", "water", "sandwich",
"glucose", "tin", "banana", "apple", "cheese", "beer", "suntan_cream",
Line 6,249:
print_output(Full_Data, 400)
 
</syntaxhighlight>
</lang>
 
{{out}}
<syntaxhighlight lang="text">
[1] "You must carry: socks"
[2] "You must carry: sunglasses"
Line 6,265:
[11] "You must carry: compass"
[12] "You must carry: map"
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
; An ITEM a list of three elements:
Line 6,325:
(trousers 42 70) (overclothes 43 75) (notecase 22 80)
(glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10)))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="racket">
'(1030 396 (map compass water sandwich glucose banana cream trousers overclothes notecase glasses socks))
</syntaxhighlight>
</lang>
Brute Force and Memoized Recursive Alternate
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 6,365:
'value: (pack-value pack)
'items: (map car pack))))
</syntaxhighlight>
</lang>
Brute Force
<langsyntaxhighlight lang="racket">
(define (show-brute)
 
Line 6,385:
 
(show-brute); takes around five seconds on my machine
</syntaxhighlight>
</lang>
Recursive Alternate
<langsyntaxhighlight lang="racket">
(define (show-memoized)
 
Line 6,412:
 
(show-memoized)
</syntaxhighlight>
</lang>
 
{{out}}
<langsyntaxhighlight lang="racket">
(weight: 396 value: 1030 items: (map compass water sandwich glucose banana cream trousers overclothes notecase glasses socks))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 6,423:
==== Brute force ====
{{works with|Rakudo|2017.01}}
<syntaxhighlight lang="raku" perl6line>my class KnapsackItem { has $.name; has $.weight; has $.unit; }
 
multi sub pokem ([], $, $v = 0) { $v }
Line 6,467:
 
my ($value, @result) = pokem @table, $MAX_WEIGHT;
say "Value = $value\nTourist put in the bag:\n " ~ @result;</langsyntaxhighlight>
{{out}}
<pre>Value = 1030
Line 6,476:
Much faster than the previous example.
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>my $raw = q:to/TABLE/;
map 9 150
compass 13 35
Line 6,535:
 
my @solution = optimal(@name.end, $sum);
put "@solution[0]: ", @solution[1].sort.join(', ');</langsyntaxhighlight>
{{out}}
<pre>1030: banana, compass, glucose, map, note-case, sandwich, socks, sunglasses, suntancream, water, waterproof overclothes, waterproof trousers
Line 6,546:
 
The term &nbsp; ''allowable items'' &nbsp; refers to all items that are of allowable weight (those that weigh within the weight criteria). &nbsp; An half metric─ton anvil was added to the list to show how overweight items are pruned from the list of items.
<langsyntaxhighlight lang="rexx">/*REXX program solves a knapsack problem (22 {+1} items with a weight restriction). */
maxWeight=400 /*the maximum weight for the knapsack. */
say 'maximum weight allowed for a knapsack:' commas(maxWeight); say
Line 6,647:
end /*k*/
end /*j*/ /* [↑] sort choices by decreasing wt. */
obj=j-1; return /*decrement J for the DO loop index*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 6,704:
=={{header|Ruby}}==
=== Brute force ===
<langsyntaxhighlight lang="ruby">KnapsackItem = Struct.new(:name, :weight, :value)
potential_items = [
KnapsackItem['map', 9, 150], KnapsackItem['compass', 13, 35],
Line 6,746:
puts "weight: #{wt}"
puts "items: #{items.join(',')}"
end</langsyntaxhighlight>
 
{{out}}
Line 6,757:
=== Dynamic Programming ===
Translated from http://sites.google.com/site/mikescoderama/Home/0-1-knapsack-problem-in-p
<langsyntaxhighlight lang="ruby">KnapsackItem = Struct.new(:name, :weight, :value)
 
def dynamic_programming_knapsack(items, max_weight)
Line 6,819:
puts "total weight: #{weight}"
puts "total value: #{value}"
end</langsyntaxhighlight>
{{out}}
<pre style='width: full; overflow: scroll'>
Line 6,831:
=={{header|Rust}}==
Dynamic Programming solution.
<langsyntaxhighlight lang="rust">use std::cmp;
 
struct Item {
Line 6,903:
println!("Total weight: {}", items.iter().map(|w| w.weight).sum::<usize>());
println!("Total value: {}", items.iter().map(|w| w.value).sum::<usize>());
}</langsyntaxhighlight>
{{out}}
<pre>map
Line 6,923:
 
Use MILP solver in SAS/OR:
<langsyntaxhighlight lang="sas">/* create SAS data set */
data mydata;
input item $1-23 weight value;
Line 6,971:
print TotalValue;
print {i in ITEMS: NumSelected[i].sol > 0.5} NumSelected;
quit;</langsyntaxhighlight>
 
Output:
Line 6,995:
=={{header|Scala}}==
{{works with|Scala|2.9.2}}
<langsyntaxhighlight Scalalang="scala">object Knapsack extends App {
 
case class Item(name: String, weight: Int, value: Int)
Line 7,093:
println(" elapsed time: "+t+" sec"+"\n")
}
}</langsyntaxhighlight>
{{out}}
<pre>packing list of items (brute force):
Line 7,135:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var raw = <<'TABLE'
map, 9, 150
compass, 13, 35
Line 7,204:
 
var sol = optimal(items.end, max_weight)
say "#{sol[0]}: #{sol[1]}"</langsyntaxhighlight>
{{out}}
<pre>
Line 7,214:
Displays the top 5 solutions and runs in about 39 seconds.
 
<syntaxhighlight lang="sql">
<lang SQL>
WITH KnapsackItems (item, [weight], value) AS
(
Line 7,261:
GO
DROP TABLE #KnapsackItems;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 7,278:
=== Dynamic Programming ===
 
<langsyntaxhighlight lang="swift">struct KnapsackItem {
var name: String
var weight: Int
Line 7,337:
let (tValue, tWeight) = kept.reduce((0, 0), { ($0.0 + $1.value, $0.1 + $1.weight) })
 
print("For a total value of \(tValue) and a total weight of \(tWeight)")</langsyntaxhighlight>
 
{{out}}
Line 7,358:
=={{header|Tcl}}==
As the saying goes, “when in doubt, try brute force”. Since there's only 22 items we can simply iterate over all possible choices.
<langsyntaxhighlight lang="tcl"># The list of items to consider, as list of lists
set items {
{map 9 150}
Line 7,432:
# Pretty-print the results
puts "Best filling has weight of [expr {[weight $best]/100.0}]kg and score [value $best]"
puts "Best items:\n\t[join [lsort [names $best]] \n\t]"</langsyntaxhighlight>
{{out}}
<pre>
Line 7,453:
=={{header|Ursala}}==
This solution follows a very similar approach to the one used in [[Knapsack problem/Bounded#Ursala]], which is to treat it as a mixed integer programming problem and solve it using an off-the-shelf library ([http://lpsolve.sourceforge.net lpsolve]).
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import flo
Line 7,496:
#show+
 
main = ~&tnS solution system items</langsyntaxhighlight>
Binary valued variables are a more specific constraint than the general mixed integer programming problem, but can be accommodated as shown using the <code>binaries</code> field in the <code>linear_system</code> specification. The additional <code>slack</code> variable is specified as continuous and non-negative with no cost or benefit so as to make the constraint equation solvable without affecting the solution.
{{out}}
Line 7,515:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">'Knapsack problem/0-1 - 12/02/2017
Option Explicit
Const maxWeight = 400
Line 7,572:
Call ChoiceBin(n + 1, ss)
End If
End Sub 'ChoiceBin</langsyntaxhighlight>
{{out}}
<pre>
Line 7,592:
=={{header|VBScript}}==
Non recurvive unfolded force version. Created by an other script. It runs 13 times faster than the recursive one.
<langsyntaxhighlight lang="vb">' Knapsack problem/0-1 - 13/02/2017
dim w(22),v(22),m(22)
data=array( "map", 9, 150, "compass", 13, 35, "water", 153, 200, _
Line 7,805:
if l(i)=1 then wlist=wlist&vbCrlf&data((i-1)*3)
next
Msgbox mid(wlist,3)&vbCrlf&vbCrlf&"weight="&xw&vbCrlf&"value="&xv,,"Knapsack - nn="&nn</langsyntaxhighlight>
{{out}}
<pre>
Line 7,827:
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">'Knapsack problem/0-1 - 12/02/2017
Option Explicit
Const maxWeight = 400
Line 7,894:
Call ChoiceBin(n + 1, ss)
End If
End Sub 'ChoiceBin</langsyntaxhighlight>
{{out}}
<pre>
Line 7,914:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2013}}
<langsyntaxhighlight lang="vbnet">'Knapsack problem/0-1 - 12/02/2017
Public Class KnapsackBin
Const knam = 0, kwei = 1, kval = 2
Line 7,997:
 
End Class 'KnapsackBin
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 8,019:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="go">struct Item {
name string
w int
Line 8,073:
}
return i0, w0, v0
}</langsyntaxhighlight>
{{out}}
<pre>
Line 8,085:
{{libheader|Wren-fmt}}
Based on the Go example, though modified to give output in tabular form.
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Fmt
 
var wants = [
Line 8,144:
}
System.print(" --- ----")
Fmt.print("totals $3d $4d", tw, tv)</langsyntaxhighlight>
 
{{out}}
Line 8,169:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \include 'code' declarations
 
int Item, Items, Weights, Values,
Line 8,225:
IntOut(0, W); ChOut(0, Tab);
IntOut(0, V); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 8,246:
=={{header|zkl}}==
{{trans|Haskell}}{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn addItem(pairs,it){ // pairs is list of (cost of:,names), it is (name,w,v)
w,left,right:=it[1],pairs[0,w],pairs[w,*];
left.extend(right.zipWith(
fcn([(t1,_)]a,[(t2,_)]b){ t1>t2 and a or b },
pairs.apply('wrap([(tot,names)]){ T(tot + it[2], names + it[0]) })))
}//--> new list of pairs</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">items:=T(T("apple", 39, 40),T("banana", 27,60), // item: (name,weight,value)
T("beer", 52, 10),T("book", 30,10),T("camera", 32, 30),
T("cheese", 23, 30),T("compass", 13,35),T("glucose", 15, 60),
Line 8,264:
(MAX_WEIGHT).pump(List,T(0,T).copy))[-1]; // nearest to max weight
weight:=items.apply('wrap(it){ knapsack[1].holds(it[0]) and it[1] }).sum(0);
knapsack.println(weight);</langsyntaxhighlight>
{{out}}
<pre>
10,343

edits