Another update from ingydotnet^djgoku
This commit is contained in:
parent
91df62d461
commit
948b86eafa
7604 changed files with 108452 additions and 22726 deletions
|
|
@ -0,0 +1,15 @@
|
|||
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<
|
||||
nib@_>0022p6>12p:212gg48*:**012gg/\-:0`3^+>,,55+%6v
|
||||
#v0pg2231$$_^#`+5g20:+1g21$_+#!:#<0#<<p22<\v84,+*8<
|
||||
*>22gg+::55*6*`\55*6*-*022gg\-:55+/68*+"."^>*"fo "v
|
||||
^6*55:,+55$$_,#!1#`+#*:#82#42#:g<g22:4,,,,,,," kg"<
|
||||
3836beef
|
||||
5443pork
|
||||
3690ham
|
||||
2445greaves
|
||||
4030flitch
|
||||
2556brawn
|
||||
3767welt
|
||||
3095salami
|
||||
5998sausage
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
(def items
|
||||
[{:name "beef" :weight 3.8 :price 36}
|
||||
{:name "pork" :weight 5.4 :price 43}
|
||||
{:name "ham" :weight 3.6 :price 90}
|
||||
{:name "graves" :weight 2.4 :price 45}
|
||||
{:name "flitch" :weight 4.0 :price 30}
|
||||
{:name "brawn" :weight 2.5 :price 56}
|
||||
{:name "welt" :weight 3.7 :price 67}
|
||||
{:name "salami" :weight 3.0 :price 95}
|
||||
{:name "sausage" :weight 5.9 :price 98}])
|
||||
|
||||
(defn per-kg [item] (/ (:price item) (:weight item)))
|
||||
|
||||
(defn rob [items capacity]
|
||||
(let [best-items (reverse (sort-by per-kg items))]
|
||||
(loop [items best-items cap capacity total 0]
|
||||
(let [item (first items)]
|
||||
(if (< (:weight item) cap)
|
||||
(do (println (str "Take all " (:name item)))
|
||||
(recur (rest items) (- cap (:weight item)) (+ total (:price item))))
|
||||
(println (format "Take %.1f kg of %s\nTotal: %.2f monies"
|
||||
cap (:name item) (+ total (* cap (per-kg item))))))))))
|
||||
|
||||
(rob items 15)
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
class
|
||||
CONTINUOUS_KNAPSACK
|
||||
|
||||
create
|
||||
make
|
||||
|
||||
feature
|
||||
|
||||
make
|
||||
local
|
||||
tup: TUPLE [name: STRING; weight: REAL_64; price: REAL_64]
|
||||
do
|
||||
create tup
|
||||
create items.make_filled (tup, 1, 9)
|
||||
create sorted.make
|
||||
sorted.extend (-36.0 / 3.8)
|
||||
sorted.extend (-43.0 / 5.4)
|
||||
sorted.extend (-90.0 / 3.6)
|
||||
sorted.extend (-45.0 / 2.4)
|
||||
sorted.extend (-30.0 / 4.0)
|
||||
sorted.extend (-56.0 / 2.5)
|
||||
sorted.extend (-67.0 / 3.7)
|
||||
sorted.extend (-95.0 / 3.0)
|
||||
sorted.extend (-98.0 / 5.9)
|
||||
tup := ["beef", 3.8, 36.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["pork", 5.4, 43.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["ham", 3.6, 90.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["greaves", 2.4, 45.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["flitch", 4.0, 30.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["brawn", 2.5, 56.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["welt", 3.7, 67.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["salami", 3.0, 95.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
tup := ["sausage", 5.9, 98.0]
|
||||
items [sorted.index_of (- tup.price / tup.weight, 1)] := tup
|
||||
find_solution
|
||||
end
|
||||
|
||||
find_solution
|
||||
-- Solution for the continuous Knapsack Problem.
|
||||
local
|
||||
maxW, value: REAL_64
|
||||
do
|
||||
maxW := 15
|
||||
across
|
||||
items as c
|
||||
loop
|
||||
if maxW - c.item.weight > 0 then
|
||||
io.put_string ("Take all: " + c.item.name + ".%N")
|
||||
value := value + c.item.price
|
||||
maxW := maxW - c.item.weight
|
||||
elseif maxW /= 0 then
|
||||
io.put_string ("Take " + maxW.truncated_to_real.out + " kg off " + c.item.name + ".%N")
|
||||
io.put_string ("The total value is " + (value + (c.item.price / c.item.weight) * maxW).truncated_to_real.out + ".")
|
||||
maxW := 0
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
items: ARRAY [TUPLE [name: STRING; weight: REAL_64; price: REAL_64]]
|
||||
|
||||
sorted: SORTED_TWO_WAY_LIST [REAL_64]
|
||||
|
||||
end
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
defmodule KnapsackProblem do
|
||||
def price_per_weight( items ), do: (for {name, weight, price} <-items, do: {name, weight, price / weight} )
|
||||
|
||||
def select( max_weight, items ) do
|
||||
{_remains, selected_items} = List.foldr( List.keysort(items, 2), {max_weight, []}, &select_until/2 )
|
||||
selected_items
|
||||
end
|
||||
|
||||
def task( max_weight, items ) do
|
||||
IO.puts "The robber takes the following to maximize the value"
|
||||
for {name, weight} <- select( max_weight, price_per_weight(items) ), do: :io.fwrite("~.2f of ~s~n", [weight, name])
|
||||
end
|
||||
|
||||
defp select_until( {name, weight, _price}, {remains, acc} ) when remains > 0 do
|
||||
selected_weight = select_until_weight( weight, remains )
|
||||
{remains - selected_weight, [{name, selected_weight} | acc]}
|
||||
end
|
||||
defp select_until( _item, acc ), do: acc
|
||||
|
||||
defp select_until_weight( weight, remains ) when weight < remains, do: weight
|
||||
defp select_until_weight( _weight, remains ), do: remains
|
||||
end
|
||||
|
||||
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} ]
|
||||
|
||||
KnapsackProblem.task( 15, items )
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
immutable KPCSupply{S<:String, T<:Real}
|
||||
item::S
|
||||
weight::T
|
||||
value::T
|
||||
uvalue::T
|
||||
end
|
||||
Base.isless(a::KPCSupply, b::KPCSupply) = a.uvalue<b.uvalue
|
||||
|
||||
function KPCSupply{S<:String, T<:Real}(item::S, weight::T, value::T)
|
||||
KPCSupply(item, weight, value, value/weight)
|
||||
end
|
||||
|
||||
function solve{S<:String, T<:Real}(store::Array{KPCSupply{S,T},1},
|
||||
capacity::T)
|
||||
ksack = KPCSupply{S,T}[]
|
||||
kweight = zero(T)
|
||||
for s in sort(store, rev=true)
|
||||
if kweight + s.weight <= capacity
|
||||
kweight += s.weight
|
||||
push!(ksack, s)
|
||||
else
|
||||
w = capacity-kweight
|
||||
v = w*s.uvalue
|
||||
push!(ksack, KPCSupply(s.item, w, v, s.uvalue))
|
||||
break
|
||||
end
|
||||
end
|
||||
return ksack
|
||||
end
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
store = [KPCSupply("beef", 38//10, 36//1),
|
||||
KPCSupply("pork", 54//10, 43//1),
|
||||
KPCSupply("ham", 36//10, 90//1),
|
||||
KPCSupply("greaves", 24//10, 45//1),
|
||||
KPCSupply("flitch", 4//1, 30//1),
|
||||
KPCSupply("brawn", 25//10, 56//1),
|
||||
KPCSupply("welt", 37//10, 67//1),
|
||||
KPCSupply("salami", 3//1, 95//1),
|
||||
KPCSupply("sausage", 59//10, 98//1)]
|
||||
|
||||
sack = solve(store, 15//1)
|
||||
|
||||
println("The store contains:")
|
||||
println(" Item Weight Unit Price")
|
||||
for s in store
|
||||
println(@sprintf("%12s %4.1f %6.2f",
|
||||
s.item, float(s.weight), float(s.uvalue)))
|
||||
end
|
||||
|
||||
println()
|
||||
println("The thief should take:")
|
||||
println(" Item Weight Value")
|
||||
for s in sack
|
||||
println(@sprintf("%12s %4.1f %6.2f",
|
||||
s.item, float(s.weight), float(s.value)))
|
||||
end
|
||||
w = mapreduce(x->x.weight, +, sack)
|
||||
v = mapreduce(x->x.value, +, sack)
|
||||
println(@sprintf("%12s %4.1f %6.2f",
|
||||
"Total", float(w), float(v)))
|
||||
|
|
@ -15,10 +15,10 @@ class KnapsackItem {
|
|||
return True;
|
||||
}
|
||||
|
||||
method Str () { sprintf "%8s %1.2f %3.2f",
|
||||
$.name,
|
||||
$.weight,
|
||||
$.price }
|
||||
method gist () { sprintf "%8s %1.2f %3.2f",
|
||||
$.name,
|
||||
$.weight,
|
||||
$.price }
|
||||
}
|
||||
|
||||
my $max-w = 15;
|
||||
|
|
@ -34,7 +34,7 @@ say "Item Portion Value";
|
|||
welt 3.7 67
|
||||
salami 3.0 95
|
||||
sausage 5.9 98 >
|
||||
==> map { KnapsackItem.new($^a, $^b, $^c) }
|
||||
==> map({ KnapsackItem.new($^a, $^b, $^c) })
|
||||
==> sort *.ppw
|
||||
{
|
||||
my $last-one = .cut-maybe($max-w);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,43 @@
|
|||
knapsack<- function(Value, Weight, Objects, Capacity){
|
||||
Fraction = rep(0, length(Value))
|
||||
Cost = Value/Weight
|
||||
#print(Cost)
|
||||
W = Weight[order(Cost, decreasing = TRUE)]
|
||||
Obs = Objects[order(Cost, decreasing = TRUE)]
|
||||
Val = Value[order(Cost, decreasing = TRUE)]
|
||||
#print(W)
|
||||
RemainCap = Capacity
|
||||
i = 1
|
||||
n = length(Cost)
|
||||
if (W[1] <= Capacity){
|
||||
Fits <- TRUE
|
||||
}
|
||||
else{
|
||||
Fits <- FALSE
|
||||
}
|
||||
while (Fits && i <= n ){
|
||||
Fraction[i] <- 1
|
||||
RemainCap <- RemainCap - W[i]
|
||||
i <- i+1
|
||||
#print(RemainCap)
|
||||
if (W[i] <= RemainCap){
|
||||
Fits <- TRUE
|
||||
}
|
||||
else{
|
||||
Fits <- FALSE
|
||||
}
|
||||
}
|
||||
#print(RemainCap)
|
||||
if (i <= n){
|
||||
Fraction[i] <- RemainCap/W[i]
|
||||
}
|
||||
names(Fraction) = Obs
|
||||
Quantity_to_take = W*Fraction
|
||||
Total_Value = sum(Val*Fraction)
|
||||
print("Fraction of available quantity to take:")
|
||||
print(round(Fraction, 3))
|
||||
print("KG of each to take:")
|
||||
print(Quantity_to_take)
|
||||
print("Total value of tasty meats:")
|
||||
print(Total_Value)
|
||||
}
|
||||
|
|
@ -1,47 +1,45 @@
|
|||
/*REXX program solves the (continuous) burglar's knapsack problem. */
|
||||
@.= /*═══════ name weight value ══════*/
|
||||
@.1 = 'flitch 4 30 '
|
||||
@.2 = 'beef 3.8 36 '
|
||||
@.3 = 'pork 5.4 43 '
|
||||
@.4 = 'greaves 2.4 45 '
|
||||
@.5 = 'brawn 2.5 56 '
|
||||
@.6 = 'welt 3.7 67 '
|
||||
@.7 = 'ham 3.6 90 '
|
||||
@.8 = 'salami 3 95 '
|
||||
@.9 = 'sausage 5.9 98 '
|
||||
parse arg maxW d . /*get possible args from the C.L.*/
|
||||
if maxW=='' | maxW==',' then maxW=15 /*burglar's knapsack max weight. */
|
||||
if d=='' | d==',' then d= 3 /*# of decimal digits in FORMAT. */
|
||||
wL=d+length('weight'); nL=d+length('total weight'); vL=d+length('value')
|
||||
/*REXX program solves the (continuous) burglar's knapsack problem. */
|
||||
@.= /*═══════ name weight value ══════*/
|
||||
@.1 = 'flitch 4 30 '
|
||||
@.2 = 'beef 3.8 36 '
|
||||
@.3 = 'pork 5.4 43 '
|
||||
@.4 = 'greaves 2.4 45 '
|
||||
@.5 = 'brawn 2.5 56 '
|
||||
@.6 = 'welt 3.7 67 '
|
||||
@.7 = 'ham 3.6 90 '
|
||||
@.8 = 'salami 3 95 '
|
||||
@.9 = 'sausage 5.9 98 '
|
||||
parse arg maxW d . /*get possible arguments from the C.L. */
|
||||
if maxW=='' | maxW==',' then maxW=15 /*the burglar's knapsack maximum weight*/
|
||||
if d=='' | d==',' then d= 3 /*number of decimal digits in FORMAT. */
|
||||
wL=d+length('weight'); nL=d+length('total weight'); vL=d+length('value')
|
||||
totW=0; totV=0
|
||||
do #=1 while @.#\==''; parse var @.# n.# w.# v.# .
|
||||
end /*#*/ /* [↑] assign to separate lists.*/
|
||||
#=#-1 /*#: number of items in @ list.*/
|
||||
call show 'unsorted item list' /*display header and the @ list.*/
|
||||
call sortD /*invoke using a descending sort.*/
|
||||
do #=1 while @.#\==''; parse var @.# n.# w.# v.# .
|
||||
end /*#*/ /* [↑] assign item to separate lists. */
|
||||
#=#-1 /*#: is the number of items in @ list.*/
|
||||
call show 'unsorted item list' /*display the header and the @ list.*/
|
||||
call sortD /*invoke sort (which sorts descending).*/
|
||||
call hdr "burglar's knapsack contents"
|
||||
do j=1 for # while totW<maxW; f=1 /*grab items*/
|
||||
if totW+w.j>=maxW then f=(maxW-totW)/w.j /*calc fract*/
|
||||
totW=totW+w.j*f; totV=totV+v.j*f /*add──►tots*/
|
||||
call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f
|
||||
end /*j*/ /*↑show item*/
|
||||
call sep; say /* [↓] $ supresses trailing Θs.*/
|
||||
do j=1 for # while totW<maxW; f=1 /*process items. */
|
||||
if totW+w.j>=maxW then f=(maxW-totW)/w.j /*calculate fract.*/
|
||||
totW=totW+w.j*f; totV=totV+v.j*f /*add ───► totals.*/
|
||||
call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f
|
||||
end /*j*/ /* [↑] show item.*/
|
||||
call sep; say; t='t' /* [↓] $ suppresses trailing zeroes.*/
|
||||
call sy left('total weight',nL,'─'), $(format(totW,,d))
|
||||
call sy left('total value',nL,'─'), , $(format(totV,,d))
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*──────────────────────────────────one─liner subroutines──────────────────────*/
|
||||
hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return
|
||||
sep: call sy copies('═',nL), copies("═",wL), copies('═',vL); return
|
||||
show: call hdr arg(1); do j=1 for #; call syf n.j,w.j,v.j; end; return
|
||||
sy: say left('',9) left(arg(1),nL) right(arg(2),wL) right(arg(3),vL); 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
|
||||
$:x=arg(1);if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x));return x
|
||||
/*──────────────────────────────────SORTD subroutine───────────────────────────*/
|
||||
sortD: do sort=2 to #; _n=n.sort; _w=w.sort; _v=v.sort /*descending. */
|
||||
do k=sort-1 by -1 to 1 while v.k/w.k<_v/_w /*order items.*/
|
||||
p=k+1; n.p=n.k; w.p=w.k; v.p=v.k /*shuffle 'em.*/
|
||||
end /*k*/ /*[↓] last one*/
|
||||
a=k+1; n.a=_n; w.a=_w; v.a=_v /*place item. */
|
||||
end /*sort*/
|
||||
return /* ↑ ↑ ↑ algorithm is OK for smallish arrays.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*────────────────────────────────────────────────────────────────────────────*/
|
||||
sortD: do s=2 to #; a=n.s; !=w.s; u=v.s /* [↓] this is a descending sort.*/
|
||||
do k=s-1 by -1 to 1 while v.k/w.k<u/!;?=k+1;n.?=n.k;w.?=w.k;v.?=v.k;end
|
||||
?=k+1; n.?=a; w.?=!; v.?=u
|
||||
end /*s*/
|
||||
return /* ↑↑↑ sort algorithm is OK for small arrays.*/
|
||||
/*──────────────────────────────────one─liner subroutines─────────────────────*/
|
||||
hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return
|
||||
sep: call sy copies('═',nL), copies("═",wL), copies('═',vL); return
|
||||
show: call hdr arg(1); do j=1 for #; call syf n.j,w.j,v.j; end; return
|
||||
sy: say left('',9) left(arg(1),nL) right(arg(2),wL) right(arg(3),vL); 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
|
||||
$: arg x; if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x));return x
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue