Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
(Knapsack problem/Continuous in FreeBASIC) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 55: | Line 55: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">V items = [(‘beef’, 3.8, 36.0), |
||
(‘pork’, 5.4, 43.0), |
(‘pork’, 5.4, 43.0), |
||
(‘ham’, 3.6, 90.0), |
(‘ham’, 3.6, 90.0), |
||
Line 83: | Line 83: | ||
print(‘ ITEM PORTION VALUE’) |
print(‘ ITEM PORTION VALUE’) |
||
print(bagged.map((n, p, a) -> ‘#10 #3.2 #3.2’.format(n, p, a)).join("\n")) |
print(bagged.map((n, p, a) -> ‘#10 #3.2 #3.2’.format(n, p, a)).join("\n")) |
||
print("\nTOTAL WEIGHT: #2.2\nTOTAL VALUE: #2.2".format(wt, val))</ |
print("\nTOTAL WEIGHT: #2.2\nTOTAL VALUE: #2.2".format(wt, val))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 99: | Line 99: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; |
||
with Ada.Float_Text_IO; |
with Ada.Float_Text_IO; |
||
with Ada.Strings.Unbounded; |
with Ada.Strings.Unbounded; |
||
Line 201: | Line 201: | ||
end loop; |
end loop; |
||
end Knapsack_Continuous; |
end Knapsack_Continuous; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 215: | Line 215: | ||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk"># syntax: GAWK -f KNAPSACK_PROBLEM_CONTINUOUS.AWK |
||
BEGIN { |
BEGIN { |
||
# arr["item,weight,price"] |
# arr["item,weight,price"] |
||
Line 257: | Line 257: | ||
exit(0) |
exit(0) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 271: | Line 271: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> INSTALL @lib$+"SORTSALIB" |
||
Sort% = FN_sortSAinit(1, 0) : REM Descending |
Sort% = FN_sortSAinit(1, 0) : REM Descending |
||
Line 309: | Line 309: | ||
PRINT '"Total weight = " ; TotalWeight " kg" |
PRINT '"Total weight = " ; TotalWeight " kg" |
||
PRINT "Total price = " ; TotalPrice |
PRINT "Total price = " ; TotalPrice |
||
END</ |
END</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Take all the salami |
<pre>Take all the salami |
||
Line 325: | Line 325: | ||
The table of weights and prices are stored as strings to make them easier to edit. Two characters for the weight (with the decimal point dropped), two characters for the price, and then the name of the item. The total numbers of items (9) is specified by the first value on the stack. |
The table of weights and prices are stored as strings to make them easier to edit. Two characters for the weight (with the decimal point dropped), two characters for the price, and then the name of the item. The total numbers of items (9) is specified by the first value on the stack. |
||
< |
<syntaxhighlight lang="befunge">9:02p>:5+::::::0\g68*-55+*\1\g68*-+\0\pv>2gg!*::!2v |
||
>\`!v|:-1p\3\0p\2\+-*86g\3\*+55-*86g\2<<1v*g21\*g2< |
>\`!v|:-1p\3\0p\2\+-*86g\3\*+55-*86g\2<<1v*g21\*g2< |
||
nib@_>0022p6>12p:212gg48*:**012gg/\-:0`3^+>,,55+%6v |
nib@_>0022p6>12p:212gg48*:**012gg/\-:0`3^+>,,55+%6v |
||
Line 339: | Line 339: | ||
3767welt |
3767welt |
||
3095salami |
3095salami |
||
5998sausage</ |
5998sausage</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 349: | Line 349: | ||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( ( fixed {function to convert a rational number to fixed point notation. |
||
The second argument is the number of decimals. } |
The second argument is the number of decimals. } |
||
= value decimals powerOf10 |
= value decimals powerOf10 |
||
Line 398: | Line 398: | ||
| out$(fixed$(!totalPrice.2)) |
| out$(fixed$(!totalPrice.2)) |
||
) |
) |
||
);</ |
);</syntaxhighlight> |
||
Output:<pre>3.5 kg of welt |
Output:<pre>3.5 kg of welt |
||
2.4 kg of greaves |
2.4 kg of greaves |
||
Line 407: | Line 407: | ||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 443: | Line 443: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight>output<pre> |
||
take all salami |
take all salami |
||
take all ham |
take all ham |
||
Line 452: | Line 452: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; //4790@3.6 |
||
class Program |
class Program |
||
{ |
{ |
||
Line 484: | Line 484: | ||
static string[] items = {"beef","pork","ham","greaves","flitch", |
static string[] items = {"beef","pork","ham","greaves","flitch", |
||
"brawn","welt","salami","sausage"}; |
"brawn","welt","salami","sausage"}; |
||
}</ |
}</syntaxhighlight> |
||
Sorting three times is expensive, |
Sorting three times is expensive, |
||
an alternative is sorting once, with an indices array. |
an alternative is sorting once, with an indices array. |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
{ |
{ |
||
Line 519: | Line 519: | ||
static string[] items = {"beef","pork","ham","greaves","flitch", |
static string[] items = {"beef","pork","ham","greaves","flitch", |
||
"brawn","welt","salami","sausage"}; |
"brawn","welt","salami","sausage"}; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include<iostream> |
||
#include<algorithm> |
#include<algorithm> |
||
#include<string.h> |
#include<string.h> |
||
Line 616: | Line 616: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 631: | Line 631: | ||
===Alternate Version=== |
===Alternate Version=== |
||
< |
<syntaxhighlight lang="cpp">// C++11 version |
||
#include <iostream> |
#include <iostream> |
||
#include <vector> |
#include <vector> |
||
Line 683: | Line 683: | ||
space -= item.weight; |
space -= item.weight; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 695: | Line 695: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
<syntaxhighlight lang="clojure"> |
|||
<lang Clojure> |
|||
; Solve Continuous Knapsack Problem |
; Solve Continuous Knapsack Problem |
||
; Nicolas Modrzyk |
; Nicolas Modrzyk |
||
Line 744: | Line 744: | ||
(rob items maxW) |
(rob items maxW) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output<pre> |
Output<pre> |
||
Take all :salami |
Take all :salami |
||
Line 755: | Line 755: | ||
===Alternate Version=== |
===Alternate Version=== |
||
<syntaxhighlight lang="clojure"> |
|||
<lang Clojure> |
|||
(def items |
(def items |
||
[{:name "beef" :weight 3.8 :price 36} |
[{:name "beef" :weight 3.8 :price 36} |
||
Line 780: | Line 780: | ||
(rob items 15) |
(rob items 15) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defstruct item |
||
(name nil :type string) |
(name nil :type string) |
||
(weight nil :type real) |
(weight nil :type real) |
||
Line 810: | Line 810: | ||
(make-item :name "sausage" :weight 5.9 :price 98)))) |
(make-item :name "sausage" :weight 5.9 :price 98)))) |
||
(loop for (name amount) in (knapsack items 15) |
(loop for (name amount) in (knapsack items 15) |
||
do (format t "~8A: ~,2F kg~%" name amount))))</ |
do (format t "~8A: ~,2F kg~%" name amount))))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>salami : 3.00 kg |
<pre>salami : 3.00 kg |
||
Line 819: | Line 819: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.string; |
||
struct Item { |
struct Item { |
||
Line 866: | Line 866: | ||
writefln("%(%s\n%)", chosen); |
writefln("%(%s\n%)", chosen); |
||
Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln; |
Item("TOTAL", chosen.sumBy!"amount", chosen.sumBy!"value").writeln; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> ITEM AMOUNT VALUE $/unit |
<pre> ITEM AMOUNT VALUE $/unit |
||
Line 877: | Line 877: | ||
===Alternative Version=== |
===Alternative Version=== |
||
< |
<syntaxhighlight lang="d">void main() { |
||
import std.stdio, std.algorithm; |
import std.stdio, std.algorithm; |
||
Line 902: | Line 902: | ||
} else |
} else |
||
return writefln("Take %.1fkg %s", left, it.item); |
return writefln("Take %.1fkg %s", left, it.item); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Take all the salami |
<pre>Take all the salami |
||
Line 911: | Line 911: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(lib 'struct) |
(lib 'struct) |
||
(lib 'sql) ;; for table |
(lib 'sql) ;; for table |
||
Line 950: | Line 950: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
<syntaxhighlight lang="eiffel"> |
|||
<lang Eiffel> |
|||
class |
class |
||
CONTINUOUS_KNAPSACK |
CONTINUOUS_KNAPSACK |
||
Line 1,025: | Line 1,025: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,038: | Line 1,038: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang="elixir">defmodule KnapsackProblem do |
||
def select( max_weight, items ) do |
def select( max_weight, items ) do |
||
Enum.sort_by( items, fn {_name, weight, price} -> - price / weight end ) |
Enum.sort_by( items, fn {_name, weight, price} -> - price / weight end ) |
||
Line 1,073: | Line 1,073: | ||
{"sausage", 5.9, 98} ] |
{"sausage", 5.9, 98} ] |
||
KnapsackProblem.task( items, 15 )</ |
KnapsackProblem.task( items, 15 )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,087: | Line 1,087: | ||
===Alternate Version=== |
===Alternate Version=== |
||
{{trans|Ruby}} |
{{trans|Ruby}} |
||
< |
<syntaxhighlight lang="elixir">defmodule KnapsackProblem do |
||
def continuous(items, max_weight) do |
def continuous(items, max_weight) do |
||
Enum.sort_by(items, fn {_item, {weight, price}} -> -price / weight end) |
Enum.sort_by(items, fn {_item, {weight, price}} -> -price / weight end) |
||
Line 1,118: | Line 1,118: | ||
sausage: {5.9, 98} ] |
sausage: {5.9, 98} ] |
||
KnapsackProblem.continuous( items, 15 )</ |
KnapsackProblem.continuous( items, 15 )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,133: | Line 1,133: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Note use of lists:foldr/2, since sort is ascending. |
Note use of lists:foldr/2, since sort is ascending. |
||
<syntaxhighlight lang="erlang"> |
|||
<lang Erlang> |
|||
-module( knapsack_problem_continuous ). |
-module( knapsack_problem_continuous ). |
||
Line 1,170: | Line 1,170: | ||
select_until_weight( Weight, Remains ) when Weight < Remains -> Weight; |
select_until_weight( Weight, Remains ) when Weight < Remains -> Weight; |
||
select_until_weight( _Weight, Remains ) -> Remains. |
select_until_weight( _Weight, Remains ) -> Remains. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,183: | Line 1,183: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
//Fill a knapsack optimally - Nigel Galloway: February 1st., 2015 |
//Fill a knapsack optimally - Nigel Galloway: February 1st., 2015 |
||
let items = [("beef", 3.8, 36);("pork", 5.4, 43);("ham", 3.6, 90);("greaves", 2.4, 45);("flitch" , 4.0, 30);("brawn", 2.5, 56);("welt", 3.7, 67);("salami" , 3.0, 95);("sausage", 5.9, 98)] |
let items = [("beef", 3.8, 36);("pork", 5.4, 43);("ham", 3.6, 90);("greaves", 2.4, 45);("flitch" , 4.0, 30);("brawn", 2.5, 56);("welt", 3.7, 67);("salami" , 3.0, 95);("sausage", 5.9, 98)] |
||
Line 1,201: | Line 1,201: | ||
| [] -> printfn "Everything taken! Total value of swag is £%0.2f; Total weight of bag is %0.2fkg" a n |
| [] -> printfn "Everything taken! Total value of swag is £%0.2f; Total weight of bag is %0.2fkg" a n |
||
take(0.0, items, 0.0) |
take(0.0, items, 0.0) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,230: | Line 1,230: | ||
{{trans|D}} |
{{trans|D}} |
||
{{works with|4tH|3.62.0}} |
{{works with|4tH|3.62.0}} |
||
< |
<syntaxhighlight lang="forth">include lib/selcsort.4th \ use a tiny sorting algorithm |
||
150 value left \ capacity in 1/10th kilo |
150 value left \ capacity in 1/10th kilo |
||
Line 1,268: | Line 1,268: | ||
; |
; |
||
knapsack</ |
knapsack</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program KNAPSACK_CONTINUOUS |
||
implicit none |
implicit none |
||
Line 1,327: | Line 1,327: | ||
write(*, "(f15.2, f8.2)") total_weight, total_value |
write(*, "(f15.2, f8.2)") total_weight, total_value |
||
end program KNAPSACK_CONTINUOUS</ |
end program KNAPSACK_CONTINUOUS</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">#define PesoMax 15.0 |
||
Type Knapsack |
Type Knapsack |
||
articulo As String*7 |
articulo As String*7 |
||
Line 1,378: | Line 1,378: | ||
Print Using "Total weight: ###.## kg"; TPeso |
Print Using "Total weight: ###.## kg"; TPeso |
||
Print Using "Total value: ###.##"; TPrecio |
Print Using "Total value: ###.##"; TPrecio |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>You can carry the following materials in the knapsack: |
<pre>You can carry the following materials in the knapsack: |
||
Line 1,392: | Line 1,392: | ||
=={{header|GNU APL}}== |
=={{header|GNU APL}}== |
||
< |
<syntaxhighlight lang="apl">⍝ Data |
||
Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage' |
Items←'beef' 'pork' 'ham' 'greaves' 'flitch' 'brawn' 'welt' 'salami' 'sausage' |
||
Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9 |
Weights←3.8 5.4 3.6 2.4 4 2.5 3.7 3 5.9 |
||
Line 1,409: | Line 1,409: | ||
⎕←'' |
⎕←'' |
||
⎕←'total cost:' TotalCost |
⎕←'total cost:' TotalCost |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,423: | Line 1,423: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 1,472: | Line 1,472: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,484: | Line 1,484: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: obvious greedy algorithm |
Solution: obvious greedy algorithm |
||
< |
<syntaxhighlight lang="groovy">import static java.math.RoundingMode.* |
||
def knapsackCont = { list, maxWeight = 15.0 -> |
def knapsackCont = { list, maxWeight = 15.0 -> |
||
Line 1,502: | Line 1,502: | ||
} |
} |
||
sack |
sack |
||
}</ |
}</syntaxhighlight> |
||
Test: |
Test: |
||
< |
<syntaxhighlight lang="groovy">def possibleItems = [ |
||
[name:'beef', weight:3.8, value:36], |
[name:'beef', weight:3.8, value:36], |
||
[name:'pork', weight:5.4, value:43], |
[name:'pork', weight:5.4, value:43], |
||
Line 1,521: | Line 1,521: | ||
contents.each { |
contents.each { |
||
printf(" name: %-7s weight: ${it.weight} value: ${it.value}\n", it.name) |
printf(" name: %-7s weight: ${it.weight} value: ${it.value}\n", it.name) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,535: | Line 1,535: | ||
We use a greedy algorithm. |
We use a greedy algorithm. |
||
< |
<syntaxhighlight lang="haskell">import Data.List (sortBy) |
||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
import Text.Printf (printf) |
import Text.Printf (printf) |
||
Line 1,583: | Line 1,583: | ||
where |
where |
||
a = floor q |
a = floor q |
||
b = q - toEnum a</ |
b = q - toEnum a</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>3 kg of salami |
<pre>3 kg of salami |
||
Line 1,593: | Line 1,593: | ||
Or similar to above (but more succinct): |
Or similar to above (but more succinct): |
||
< |
<syntaxhighlight lang="haskell">import Data.List (sortBy) |
||
import Data.Ord (comparing) |
import Data.Ord (comparing) |
||
import Text.Printf (printf) |
import Text.Printf (printf) |
||
Line 1,618: | Line 1,618: | ||
| otherwise = printf "Take %.2f kg of the %s\n" (k :: Float) name |
| otherwise = printf "Take %.2f kg of the %s\n" (k :: Float) name |
||
main = solution 15 items</ |
main = solution 15 items</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Take all the salami |
<pre>Take all the salami |
||
Line 1,628: | Line 1,628: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
This implements the greedy algorithm. This also uses a Unicon extension to ''reverse'' which reverses a list. In Icon, an IPL procedure is available to do the same. |
This implements the greedy algorithm. This also uses a Unicon extension to ''reverse'' which reverses a list. In Icon, an IPL procedure is available to do the same. |
||
< |
<syntaxhighlight lang="icon">link printf |
||
procedure main() |
procedure main() |
||
Line 1,663: | Line 1,663: | ||
item("salami", 3.0, 95), |
item("salami", 3.0, 95), |
||
item("sausage", 5.9, 98) ] |
item("sausage", 5.9, 98) ] |
||
end</ |
end</syntaxhighlight> |
||
{{libheader|Icon Programming Library}} |
{{libheader|Icon Programming Library}} |
||
Line 1,679: | Line 1,679: | ||
We take as much as we can of the most valuable items first, and continue until we run out of space. Only one item needs to be cut. |
We take as much as we can of the most valuable items first, and continue until we run out of space. Only one item needs to be cut. |
||
< |
<syntaxhighlight lang="j">'names numbers'=:|:;:;._2]0 :0 |
||
beef 3.8 36 |
beef 3.8 36 |
||
pork 5.4 43 |
pork 5.4 43 |
||
Line 1,693: | Line 1,693: | ||
order=: \:prices%weights |
order=: \:prices%weights |
||
take=: 15&<.&.(+/\) order{weights |
take=: 15&<.&.(+/\) order{weights |
||
result=: (*take)#(order{names),.' ',.":,.take</ |
result=: (*take)#(order{names),.' ',.":,.take</syntaxhighlight> |
||
This gives the result: |
This gives the result: |
||
Line 1,703: | Line 1,703: | ||
For a total value of: |
For a total value of: |
||
< |
<syntaxhighlight lang="j"> +/prices * (take/:order) % weights |
||
349.378</ |
349.378</syntaxhighlight> |
||
See [[Knapsack_problem/Continuous/J]] for some comments on intermediate results... |
See [[Knapsack_problem/Continuous/J]] for some comments on intermediate results... |
||
Line 1,711: | Line 1,711: | ||
Greedy solution. |
Greedy solution. |
||
< |
<syntaxhighlight lang="java"> |
||
package hu.pj.alg.test; |
package hu.pj.alg.test; |
||
Line 1,784: | Line 1,784: | ||
} |
} |
||
} // class</ |
} // class</syntaxhighlight> |
||
< |
<syntaxhighlight lang="java"> |
||
package hu.pj.alg; |
package hu.pj.alg; |
||
Line 1,862: | Line 1,862: | ||
} |
} |
||
} // class</ |
} // class</syntaxhighlight> |
||
< |
<syntaxhighlight lang="java"> |
||
package hu.pj.obj; |
package hu.pj.obj; |
||
Line 1,923: | Line 1,923: | ||
} |
} |
||
} // class</ |
} // class</syntaxhighlight> |
||
output: |
output: |
||
Line 1,941: | Line 1,941: | ||
{{ works with|jq|1.4}} |
{{ works with|jq|1.4}} |
||
< |
<syntaxhighlight lang="jq"># continuous_knapsack(W) expects the input to be |
||
# an array of objects {"name": _, "weight": _, "value": _} |
# an array of objects {"name": _, "weight": _, "value": _} |
||
# where "value" is the value of the given weight of the object. |
# where "value" is the value of the given weight of the object. |
||
Line 1,962: | Line 1,962: | ||
| (.[] | {name, weight}), |
| (.[] | {name, weight}), |
||
"Total value: \( map(.value) | add)", |
"Total value: \( map(.value) | add)", |
||
"Total weight: \(W - $remainder)" ;</ |
"Total weight: \(W - $remainder)" ;</syntaxhighlight> |
||
'''The task:''' |
'''The task:''' |
||
< |
<syntaxhighlight lang="jq">def items: [ |
||
{ "name": "beef", "weight": 3.8, "value": 36}, |
{ "name": "beef", "weight": 3.8, "value": 36}, |
||
{ "name": "pork", "weight": 5.4, "value": 43}, |
{ "name": "pork", "weight": 5.4, "value": 43}, |
||
Line 1,975: | Line 1,975: | ||
{ "name": "sausage", "weight": 5.9, "value": 98} ]; |
{ "name": "sausage", "weight": 5.9, "value": 98} ]; |
||
items | continuous_knapsack(15)</ |
items | continuous_knapsack(15)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="sh">$ jq -r -c -n -f knapsack_continuous.jq |
||
{"name":"salami","weight":3} |
{"name":"salami","weight":3} |
||
{"name":"ham","weight":3.6} |
{"name":"ham","weight":3.6} |
||
Line 1,984: | Line 1,984: | ||
{"name":"welt","weight":3.5000000000000004} |
{"name":"welt","weight":3.5000000000000004} |
||
Total value: 349.3783783783784 |
Total value: 349.3783783783784 |
||
Total weight: 15</ |
Total weight: 15</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 1,992: | Line 1,992: | ||
'''Type and Functions''': |
'''Type and Functions''': |
||
< |
<syntaxhighlight lang="julia">using Printf |
||
struct KPCSupply{T<:Real} |
struct KPCSupply{T<:Real} |
||
Line 2,023: | Line 2,023: | ||
end |
end |
||
return sack |
return sack |
||
end</ |
end</syntaxhighlight> |
||
'''Main''': |
'''Main''': |
||
< |
<syntaxhighlight lang="julia">store = [KPCSupply("beef", 38//10, 36), |
||
KPCSupply("pork", 54//10, 43), |
KPCSupply("pork", 54//10, 43), |
||
KPCSupply("ham", 36//10, 90), |
KPCSupply("ham", 36//10, 90), |
||
Line 2,039: | Line 2,039: | ||
println("The store contains:\n - ", join(store, "\n - ")) |
println("The store contains:\n - ", join(store, "\n - ")) |
||
println("\nThe thief should take::\n - ", join(sack, "\n - ")) |
println("\nThe thief should take::\n - ", join(sack, "\n - ")) |
||
@printf("\nTotal value in the sack: %.2f €\n", sum(getfield.(sack, :value)))</ |
@printf("\nTotal value in the sack: %.2f €\n", sum(getfield.(sack, :value)))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,063: | Line 2,063: | ||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
data class Item(val name: String, val weight: Double, val value: Double) |
data class Item(val name: String, val weight: Double, val value: Double) |
||
Line 2,109: | Line 2,109: | ||
println("----------- ------ ------") |
println("----------- ------ ------") |
||
println("${itemCount} items 15.0 ${"%6.2f".format(sumValue)}") |
println("${itemCount} items 15.0 ${"%6.2f".format(sumValue)}") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,128: | Line 2,128: | ||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Knapsack { |
Module Knapsack { |
||
Form 60, 40 |
Form 60, 40 |
||
Line 2,210: | Line 2,210: | ||
} |
} |
||
Knapsack |
Knapsack |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output the same as other examples, with some color. |
Output the same as other examples, with some color. |
||
Line 2,218: | Line 2,218: | ||
The output is then all items prior to this one, along with that item corrected for it's excess weighter (overW) |
The output is then all items prior to this one, along with that item corrected for it's excess weighter (overW) |
||
< |
<syntaxhighlight lang="mathematica">Knapsack[shop_, capacity_] := Block[{sortedTable, overN, overW, output}, |
||
sortedTable = SortBy[{#1, #2, #3, #3/#2} & @@@ shop, -#[[4]] &]; |
sortedTable = SortBy[{#1, #2, #3, #3/#2} & @@@ shop, -#[[4]] &]; |
||
overN = Position[Accumulate[sortedTable[[1 ;;, 2]]], a_ /; a > capacity, 1,1][[1, 1]]; |
overN = Position[Accumulate[sortedTable[[1 ;;, 2]]], a_ /; a > capacity, 1,1][[1, 1]]; |
||
Line 2,226: | Line 2,226: | ||
output[[-1, 2]] = output[[-1, 2]] - overW; |
output[[-1, 2]] = output[[-1, 2]] - overW; |
||
output[[-1, 3]] = output[[-1, 2]] output[[-1, 4]]; |
output[[-1, 3]] = output[[-1, 2]] output[[-1, 4]]; |
||
Append[output[[1 ;;, 1 ;; 3]], {"Total",Sequence @@ Total[output[[1 ;;, 2 ;; 3]]]}]]</ |
Append[output[[1 ;;, 1 ;; 3]], {"Total",Sequence @@ Total[output[[1 ;;, 2 ;; 3]]]}]]</syntaxhighlight> |
||
A test using the specified data: |
A test using the specified data: |
||
< |
<syntaxhighlight lang="mathematica">weightPriceTable = |
||
{{"beef", 3.8, 36}, {"pork", 5.4, 43}, {"ham", 3.6, 90}, {"greaves", 2.4, 45}, {"flitch", 4., 30}, |
{{"beef", 3.8, 36}, {"pork", 5.4, 43}, {"ham", 3.6, 90}, {"greaves", 2.4, 45}, {"flitch", 4., 30}, |
||
{"brawn", 2.5, 56}, {"welt", 3.7, 67}, {"salami", 3., 95}, {"sausage", 5.9, 98}}; |
{"brawn", 2.5, 56}, {"welt", 3.7, 67}, {"salami", 3., 95}, {"sausage", 5.9, 98}}; |
||
Line 2,241: | Line 2,241: | ||
welt 3.5 63.3784 |
welt 3.5 63.3784 |
||
Total 15. 349.378 |
Total 15. 349.378 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathprog}}== |
=={{header|Mathprog}}== |
||
<lang>/*Knapsack |
<syntaxhighlight lang="text">/*Knapsack |
||
This model finds the optimal packing of a knapsack |
This model finds the optimal packing of a knapsack |
||
Line 2,274: | Line 2,274: | ||
sausage 5.9 98 |
sausage 5.9 98 |
||
; |
; |
||
end;</ |
end;</syntaxhighlight> |
||
The solution is here at [[Knapsack problem/Continuous/Mathprog]]. |
The solution is here at [[Knapsack problem/Continuous/Mathprog]]. |
||
=={{header|MiniZinc}}== |
=={{header|MiniZinc}}== |
||
<syntaxhighlight lang="minizinc"> |
|||
<lang MiniZinc> |
|||
%Knapsack Continuous. Nigel Galloway: October 7th., 2020. |
%Knapsack Continuous. Nigel Galloway: October 7th., 2020. |
||
enum Items={beef,pork,ham,greaves,flitch,brawn,welt,salami,sausage}; |
enum Items={beef,pork,ham,greaves,flitch,brawn,welt,salami,sausage}; |
||
Line 2,291: | Line 2,291: | ||
solve maximize wValue; |
solve maximize wValue; |
||
output[concat([let {string: g=show(quantity[n])} in "Take "++(if g==show(weight[n]) then "all" else g endif)++" of \(n)\n" | n in Items where show(quantity[n])!="0.0"])++"\nTotal Weight=\(wTaken) Total Value="++show_float(4,2,wValue)] |
output[concat([let {string: g=show(quantity[n])} in "Take "++(if g==show(weight[n]) then "all" else g endif)++" of \(n)\n" | n in Items where show(quantity[n])!="0.0"])++"\nTotal Weight=\(wTaken) Total Value="++show_float(4,2,wValue)] |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,303: | Line 2,303: | ||
</pre> |
</pre> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import algorithm |
||
import strformat |
import strformat |
||
Line 2,340: | Line 2,340: | ||
break |
break |
||
echo fmt"Total value: {value:.2f}"</ |
echo fmt"Total value: {value:.2f}"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,353: | Line 2,353: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let items = |
||
[ "beef", 3.8, 36; |
[ "beef", 3.8, 36; |
||
"pork", 5.4, 43; |
"pork", 5.4, 43; |
||
Line 2,386: | Line 2,386: | ||
Printf.printf " %7s: %6.2f %6.2f\n" last rem_weight last_price; |
Printf.printf " %7s: %6.2f %6.2f\n" last rem_weight last_price; |
||
Printf.printf " Total Price: %.3f\n" (float price +. last_price); |
Printf.printf " Total Price: %.3f\n" (float price +. last_price); |
||
;;</ |
;;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,400: | Line 2,400: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">[ |
||
[ "beef", 3.8, 36 ], [ "pork", 5.4, 43 ], [ "ham", 3.6, 90 ], |
[ "beef", 3.8, 36 ], [ "pork", 5.4, 43 ], [ "ham", 3.6, 90 ], |
||
[ "greaves", 2.4, 45 ], [ "flitch", 4.0, 30 ], [ "brawn", 2.5, 56 ], |
[ "greaves", 2.4, 45 ], [ "flitch", 4.0, 30 ], [ "brawn", 2.5, 56 ], |
||
Line 2,417: | Line 2,417: | ||
"And part of" . item first . " :" . dup .cr |
"And part of" . item first . " :" . dup .cr |
||
item third * item second / value + "Total value :" . .cr break |
item third * item second / value + "Total value :" . .cr break |
||
] ;</ |
] ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,433: | Line 2,433: | ||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang="oorexx">/*-------------------------------------------------------------------- |
||
* 20.09.2014 Walter Pachl translated from REXX version 2 |
* 20.09.2014 Walter Pachl translated from REXX version 2 |
||
* utilizing ooRexx features like objects, array(s) and sort |
* utilizing ooRexx features like objects, array(s) and sort |
||
Line 2,507: | Line 2,507: | ||
Otherwise res='-1' |
Otherwise res='-1' |
||
End |
End |
||
Return res</ |
Return res</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,530: | Line 2,530: | ||
total 15.000 349.378</pre> |
total 15.000 349.378</pre> |
||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang="oorexx">/*-------------------------------------------------------------------- |
||
* 20.09.2014 Walter Pachl translated from REXX version 2 |
* 20.09.2014 Walter Pachl translated from REXX version 2 |
||
* utilizing ooRexx features like objects, array(s) and sort |
* utilizing ooRexx features like objects, array(s) and sort |
||
Line 2,602: | Line 2,602: | ||
Expose vpu |
Expose vpu |
||
use Arg other |
use Arg other |
||
return -sign(vpu - other~vpu)</ |
return -sign(vpu - other~vpu)</syntaxhighlight> |
||
Output is the same as for version 1. |
Output is the same as for version 1. |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">my @items = sort { $b->[2]/$b->[1] <=> $a->[2]/$a->[1] } |
||
( |
( |
||
[qw'beef 3.8 36'], |
[qw'beef 3.8 36'], |
||
Line 2,636: | Line 2,636: | ||
print "-" x 40, "\ntotal value: $value\n"; |
print "-" x 40, "\ntotal value: $value\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output:<pre>item fraction weight value |
Output:<pre>item fraction weight value |
||
salami all 3.0 95 |
salami all 3.0 95 |
||
Line 2,648: | Line 2,648: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">constant</span> <span style="color: #000000;">meats</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> |
<span style="color: #008080;">constant</span> <span style="color: #000000;">meats</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span> |
||
Line 2,680: | Line 2,680: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Total value: %f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">worth</span><span style="color: #0000FF;">})</span> |
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Total value: %f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">worth</span><span style="color: #0000FF;">})</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,692: | Line 2,692: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">/* Added by @1x24. Translated from C++. Uses the PHP 7.x spaceship operator */ |
||
$data = [ |
$data = [ |
||
[ |
[ |
||
Line 2,756: | Line 2,756: | ||
$limit -= $item['weight']; |
$limit -= $item['weight']; |
||
endforeach; |
endforeach; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre>Take all the salami |
<pre>Take all the salami |
||
Line 2,765: | Line 2,765: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
< |
<syntaxhighlight lang="picat">go => |
||
items(Items), |
items(Items), |
||
weights(Weights), |
weights(Weights), |
||
Line 2,810: | Line 2,810: | ||
items([beef,pork,ham,greaves,flitch,brawn,welt,salami,sausage]). |
items([beef,pork,ham,greaves,flitch,brawn,welt,salami,sausage]). |
||
weights([3.8,5.4,3.6,2.4,4.0,2.5,3.7,3.0,5.9]). |
weights([3.8,5.4,3.6,2.4,4.0,2.5,3.7,3.0,5.9]). |
||
values([36,43,90,45,30,56,67,95,98]).</ |
values([36,43,90,45,30,56,67,95,98]).</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,822: | Line 2,822: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(scl 2) |
||
(de *Items |
(de *Items |
||
Line 2,854: | Line 2,854: | ||
NIL |
NIL |
||
(format (sum cadr K) *Scl) |
(format (sum cadr K) *Scl) |
||
(format (sum caddr K) *Scl) ) )</ |
(format (sum caddr K) *Scl) ) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> salami 3.00 95.00 |
<pre> salami 3.00 95.00 |
||
Line 2,864: | Line 2,864: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">*process source xref attributes; |
||
KNAPSACK_CONTINUOUS: Proc Options(main); |
KNAPSACK_CONTINUOUS: Proc Options(main); |
||
/*-------------------------------------------------------------------- |
/*-------------------------------------------------------------------- |
||
Line 2,938: | Line 2,938: | ||
item(i).value = value; |
item(i).value = value; |
||
End; |
End; |
||
End;</ |
End;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,962: | Line 2,962: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Works with SWI-Prolog and <b>library(simplex)</b> written by <b>Markus Triska</b> |
Works with SWI-Prolog and <b>library(simplex)</b> written by <b>Markus Triska</b> |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(simplex)). |
||
% tuples (name, weights, value). |
% tuples (name, weights, value). |
||
knapsack :- |
knapsack :- |
||
Line 3,028: | Line 3,028: | ||
print_results(S, A1, A2, A3, T, TN, W2, V2). |
print_results(S, A1, A2, A3, T, TN, W2, V2). |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output : |
Output : |
||
<pre> ?- knapsack. |
<pre> ?- knapsack. |
||
Line 3,041: | Line 3,041: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Using the greedy algorithm. |
Using the greedy algorithm. |
||
< |
<syntaxhighlight lang="purebasic">Structure item |
||
name.s |
name.s |
||
weight.f ;units are kilograms (kg) |
weight.f ;units are kilograms (kg) |
||
Line 3,112: | Line 3,112: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf </ |
EndIf </syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>Maximal weight = 15 kg |
<pre>Maximal weight = 15 kg |
||
Line 3,127: | Line 3,127: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
I think this greedy algorithm of taking the largest amounts of items ordered by their value per unit weight is maximal: |
I think this greedy algorithm of taking the largest amounts of items ordered by their value per unit weight is maximal: |
||
< |
<syntaxhighlight lang="python"># NAME, WEIGHT, VALUE (for this weight) |
||
items = [("beef", 3.8, 36.0), |
items = [("beef", 3.8, 36.0), |
||
("pork", 5.4, 43.0), |
("pork", 5.4, 43.0), |
||
Line 3,156: | Line 3,156: | ||
print(" ITEM PORTION VALUE") |
print(" ITEM PORTION VALUE") |
||
print("\n".join("%10s %6.2f %6.2f" % item for item in bagged)) |
print("\n".join("%10s %6.2f %6.2f" % item for item in bagged)) |
||
print("\nTOTAL WEIGHT: %5.2f\nTOTAL VALUE: %5.2f" % (wt, val))</ |
print("\nTOTAL WEIGHT: %5.2f\nTOTAL VALUE: %5.2f" % (wt, val))</syntaxhighlight> |
||
'''Sample Output''' |
'''Sample Output''' |
||
Line 3,171: | Line 3,171: | ||
=={{header|R}}== |
=={{header|R}}== |
||
Translated into r-script by Shana White (vandersm@mail.uc.edu) from pseudocode found in 'Algorithms: Sequential Parallel and Distributed', by Kenneth A. Berman and Jerome L. Paul |
Translated into r-script by Shana White (vandersm@mail.uc.edu) from pseudocode found in 'Algorithms: Sequential Parallel and Distributed', by Kenneth A. Berman and Jerome L. Paul |
||
<syntaxhighlight lang="r"> |
|||
<lang r> |
|||
knapsack<- function(Value, Weight, Objects, Capacity){ |
knapsack<- function(Value, Weight, Objects, Capacity){ |
||
Fraction = rep(0, length(Value)) |
Fraction = rep(0, length(Value)) |
||
Line 3,214: | Line 3,214: | ||
print("Total value of tasty meats:") |
print("Total value of tasty meats:") |
||
print(Total_Value) |
print(Total_Value) |
||
}</ |
}</syntaxhighlight> |
||
'''Sample Input''' |
'''Sample Input''' |
||
Line 3,235: | Line 3,235: | ||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
(define shop-inventory |
(define shop-inventory |
||
'((beef 3.8 36) |
'((beef 3.8 36) |
||
Line 3,279: | Line 3,279: | ||
(call-with-values (lambda () (continuous-knapsack shop-inventory null 15 0)) |
(call-with-values (lambda () (continuous-knapsack shop-inventory null 15 0)) |
||
report-knapsack)</ |
report-knapsack)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,294: | Line 3,294: | ||
{{works with|rakudo|2015-09-16}} |
{{works with|rakudo|2015-09-16}} |
||
This Solutions sorts the item by WEIGHT/VALUE |
This Solutions sorts the item by WEIGHT/VALUE |
||
<lang |
<syntaxhighlight lang="raku" line>class KnapsackItem { |
||
has $.name; |
has $.name; |
||
has $.weight is rw; |
has $.weight is rw; |
||
Line 3,337: | Line 3,337: | ||
$max-w -= .weight; |
$max-w -= .weight; |
||
last if $last-one; |
last if $last-one; |
||
}</ |
}</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre>Item Portion Value |
<pre>Item Portion Value |
||
Line 3,350: | Line 3,350: | ||
Originally used the Fortran program as a prototype. |
Originally used the Fortran program as a prototype. |
||
<br>Some amount of code was added to format the output better. |
<br>Some amount of code was added to format the output better. |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm solves the continuous burglar's knapsack problem; items with weight and value*/ |
||
@.= /*═══════ name weight value ══════*/ |
@.= /*═══════ name weight value ══════*/ |
||
@.1 = 'flitch 4 30 ' |
@.1 = 'flitch 4 30 ' |
||
Line 3,391: | Line 3,391: | ||
syf: call sy arg(1), $(format(arg(2), , d)), $(format(arg(3), , d)); return |
syf: call sy arg(1), $(format(arg(2), , d)), $(format(arg(3), , d)); return |
||
title: call sy center('item',nL), center("weight", wL), center('value', vL); return |
title: call sy center('item',nL), center("weight", wL), center('value', vL); return |
||
$: parse arg x;if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x)); return x</ |
$: parse arg x;if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x)); return x</syntaxhighlight> |
||
'''output''' using the default inputs of: <tt> 15 3 </tt> |
'''output''' using the default inputs of: <tt> 15 3 </tt> |
||
<pre> |
<pre> |
||
Line 3,425: | Line 3,425: | ||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang="rexx"> /*-------------------------------------------------------------------- |
||
* 19.09.2014 Walter Pachl translated from FORTRAN |
* 19.09.2014 Walter Pachl translated from FORTRAN |
||
* While this program works with all REXX interpreters, |
* While this program works with all REXX interpreters, |
||
Line 3,501: | Line 3,501: | ||
input.i=name'*'weight'*'value |
input.i=name'*'weight'*'value |
||
input.0=i |
input.0=i |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre># vpu name weight value |
<pre># vpu name weight value |
||
Line 3,524: | Line 3,524: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">items = [ [:beef , 3.8, 36], |
||
[:pork , 5.4, 43], |
[:pork , 5.4, 43], |
||
[:ham , 3.6, 90], |
[:ham , 3.6, 90], |
||
Line 3,543: | Line 3,543: | ||
break |
break |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,557: | Line 3,557: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
{{incorrect|Run BASIC}} |
{{incorrect|Run BASIC}} |
||
< |
<syntaxhighlight lang="runbasic">dim name$(9) |
||
dim wgt(9) |
dim wgt(9) |
||
dim price(9) |
dim price(9) |
||
Line 3,613: | Line 3,613: | ||
print "-------- Total ";using("###.#",totTake);chr$(9);"Weight: ";totWgt |
print "-------- Total ";using("###.#",totTake);chr$(9);"Weight: ";totWgt |
||
end if |
end if |
||
next i</ |
next i</syntaxhighlight>Output: |
||
<pre>Best 2 Options |
<pre>Best 2 Options |
||
Line 3,624: | Line 3,624: | ||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
let items: [(&str, f32, u8); 9] = [ |
let items: [(&str, f32, u8); 9] = [ |
||
("beef", 3.8, 36), |
("beef", 3.8, 36), |
||
Line 3,657: | Line 3,657: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> Output:<pre> |
||
Grab 3.0 kgs of salami |
Grab 3.0 kgs of salami |
||
Grab 3.6 kgs of ham |
Grab 3.6 kgs of ham |
||
Line 3,667: | Line 3,667: | ||
=={{header|SAS}}== |
=={{header|SAS}}== |
||
Use LP solver in SAS/OR: |
Use LP solver in SAS/OR: |
||
< |
<syntaxhighlight lang="sas">/* create SAS data set */ |
||
data mydata; |
data mydata; |
||
input item $ weight value; |
input item $ weight value; |
||
Line 3,702: | Line 3,702: | ||
print TotalValue; |
print TotalValue; |
||
print {i in ITEMS: WeightSelected[i].sol > 1e-3} WeightSelected; |
print {i in ITEMS: WeightSelected[i].sol > 1e-3} WeightSelected; |
||
quit;</ |
quit;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 3,717: | Line 3,717: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===Functional approach (Tail recursive)=== |
===Functional approach (Tail recursive)=== |
||
< |
<syntaxhighlight lang="scala">import scala.annotation.tailrec |
||
object ContinousKnapsackForRobber extends App { |
object ContinousKnapsackForRobber extends App { |
||
Line 3,773: | Line 3,773: | ||
println(packer(sortedItems, Lootsack(Nil))) |
println(packer(sortedItems, Lootsack(Nil))) |
||
}</ |
}</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>100.00% Salami 3.0 95.00 |
<pre>100.00% Salami 3.0 95.00 |
||
Line 3,785: | Line 3,785: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">var items = |
||
[ |
[ |
||
[:beef, 3.8, 36], |
[:beef, 3.8, 36], |
||
Line 3,814: | Line 3,814: | ||
} |
} |
||
say "#{'-'*28}\ntotal value: #{'%.14g' % value }"</ |
say "#{'-'*28}\ntotal value: #{'%.14g' % value }"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,828: | Line 3,828: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
# Uses the trivial greedy algorithm |
# Uses the trivial greedy algorithm |
||
Line 3,864: | Line 3,864: | ||
# We return the total value too, purely for convenience |
# We return the total value too, purely for convenience |
||
return [list $result $totalValue] |
return [list $result $totalValue] |
||
}</ |
}</syntaxhighlight> |
||
Driver for this particular problem: |
Driver for this particular problem: |
||
< |
<syntaxhighlight lang="tcl">set items { |
||
{beef 3.8 36} |
{beef 3.8 36} |
||
{pork 5.4 43} |
{pork 5.4 43} |
||
Line 3,884: | Line 3,884: | ||
lassign $item name mass value |
lassign $item name mass value |
||
puts [format "\t%.1fkg of %s, value %.2f" $mass $name $value] |
puts [format "\t%.1fkg of %s, value %.2f" $mass $name $value] |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,901: | Line 3,901: | ||
[http://www.gnu.org/software/glpk/glpk.html glpk] depending on the |
[http://www.gnu.org/software/glpk/glpk.html glpk] depending on the |
||
[http://www.basis.netii.net/avram run-time system] configuration). |
[http://www.basis.netii.net/avram run-time system] configuration). |
||
< |
<syntaxhighlight lang="ursala">#import flo |
||
#import lin |
#import lin |
||
Line 3,927: | Line 3,927: | ||
#cast %em |
#cast %em |
||
main = solution system items</ |
main = solution system items</syntaxhighlight> |
||
output: |
output: |
||
<pre>< |
<pre>< |
||
Line 3,937: | Line 3,937: | ||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">struct Item { |
||
item string |
item string |
||
weight f64 |
weight f64 |
||
Line 3,978: | Line 3,978: | ||
} |
} |
||
//println(items) |
//println(items) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,993: | Line 3,993: | ||
{{libheader|Wren-math}} |
{{libheader|Wren-math}} |
||
{{libheader|Wren-sort}} |
{{libheader|Wren-sort}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/fmt" for Fmt |
||
import "/math" for Math |
import "/math" for Math |
||
import "/sort" for Sort |
import "/sort" for Sort |
||
Line 4,046: | Line 4,046: | ||
} |
} |
||
System.print("----------- ------ ------") |
System.print("----------- ------ ------") |
||
Fmt.print("$d items 15.0 $6.2f", itemCount, sumValue)</ |
Fmt.print("$d items 15.0 $6.2f", itemCount, sumValue)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,062: | Line 4,062: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">int Name, Price, I, BestItem; |
||
real Weight, Best, ItemWt, TotalWt; |
real Weight, Best, ItemWt, TotalWt; |
||
def Items = 9; |
def Items = 9; |
||
Line 4,091: | Line 4,091: | ||
Text(0, Name(BestItem)); CrLf(0); |
Text(0, Name(BestItem)); CrLf(0); |
||
until TotalWt >= 15.0; \all we can steal |
until TotalWt >= 15.0; \all we can steal |
||
]</ |
]</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,104: | Line 4,104: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
{{trans|C}} |
{{trans|C}} |
||
< |
<syntaxhighlight lang="zkl">items:=List( T(3.8, 36.0, "beef"), T(5.4, 43.0, "pork"), // weight, value, name |
||
T(3.6, 90.0, "ham"), T(2.4, 45.0, "greaves"), |
T(3.6, 90.0, "ham"), T(2.4, 45.0, "greaves"), |
||
T(4.0, 30.0, "flitch"),T(2.5, 56.0, "brawn"), |
T(4.0, 30.0, "flitch"),T(2.5, 56.0, "brawn"), |
||
Line 4,117: | Line 4,117: | ||
if (space >= w){ println("take all ",nm); space-=w } |
if (space >= w){ println("take all ",nm); space-=w } |
||
else{ println("take %gkg of %gkg of %s".fmt(space,w,nm)); break } |
else{ println("take %gkg of %gkg of %s".fmt(space,w,nm)); break } |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |