Knapsack problem/Continuous: Difference between revisions
Content added Content deleted
(Knapsack problem/Continuous in FreeBASIC) |
|||
Line 1,328: | Line 1,328: | ||
end program KNAPSACK_CONTINUOUS</lang> |
end program KNAPSACK_CONTINUOUS</lang> |
||
=={{header|FreeBASIC}}== |
|||
<lang freebasic>#define PesoMax 15.0 |
|||
Type Knapsack |
|||
articulo As String*7 |
|||
peso As Double |
|||
precio As Double |
|||
End Type |
|||
'build item list |
|||
Dim item(1 To 9) As Knapsack => { _ |
|||
("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)} |
|||
Dim As Boolean Roba(Ubound(item)) |
|||
Dim As Double PrecioXPeso(Ubound(item)) |
|||
Dim As Integer i, MejorArticulo |
|||
Dim As Double Mejor, PesoArtic, TotalPeso = 0, TPeso = 0, TPrecio = 0, temp |
|||
For i = 1 To Ubound(item) |
|||
PrecioXPeso(i) = item(i).precio / item(i).peso |
|||
Roba(i) = False |
|||
Next i |
|||
Print "You can carry the following materials in the knapsack: " |
|||
Do |
|||
Mejor = 0 |
|||
For i = 1 To Ubound(item) |
|||
If Not Roba(i) And PrecioXPeso(i) > Mejor Then |
|||
Mejor = PrecioXPeso(i) |
|||
MejorArticulo = i |
|||
End If |
|||
Next i |
|||
Roba(MejorArticulo) = True 'take item |
|||
PesoArtic = item(MejorArticulo).peso 'get its weight |
|||
TotalPeso += PesoArtic 'add to total weight |
|||
If TotalPeso > PesoMax Then 'if total is too much, reduce |
|||
PesoArtic -= TotalPeso - PesoMax 'item weight by amount it's over |
|||
End If |
|||
Print Using "##.# kg of "; PesoArtic; 'show weight and item |
|||
TPeso += PesoArtic |
|||
Print item(MejorArticulo).articulo; |
|||
temp = PesoArtic * item(MejorArticulo).precio / item(MejorArticulo).peso |
|||
TPrecio += temp |
|||
Print Chr(9); Using "(Value = ##.###)"; temp |
|||
Loop Until TotalPeso >= PesoMax 'all we can steal |
|||
Print !"\nMaximal weight:"; PesoMax; " kg" |
|||
Print Using "Total weight: ###.## kg"; TPeso |
|||
Print Using "Total value: ###.##"; TPrecio |
|||
Sleep</lang> |
|||
{{out}} |
|||
<pre>You can carry the following materials in the knapsack: |
|||
3.0 kg salami (Value = 95.000) |
|||
3.6 kg ham (Value = 90.000) |
|||
2.5 kg brawn (Value = 56.000) |
|||
2.4 kg greaves (Value = 45.000) |
|||
3.5 kg welt (Value = 63.378) |
|||
Maximal weight: 15 kg |
|||
Total weight: 15.00 kg |
|||
Total value: 349.38</pre> |
|||
=={{header|GNU APL}}== |
=={{header|GNU APL}}== |