Add tasks for all the new languages

This commit is contained in:
Tina Müller 2016-12-05 23:44:36 +01:00
parent 9dc3c2bb62
commit bba7bfd280
13208 changed files with 134745 additions and 0 deletions

View file

@ -0,0 +1,2 @@
module knapsack "1.0.0" {
}

View file

@ -0,0 +1,82 @@
shared void run() {
value knapsack = pack(items, empty(400));
print(knapsack);
}
class Item(name,weight,theValue) {
String name;
shared Integer weight;
shared Float theValue;
shared actual String string = "item(``name``, ``weight``, ``theValue``)";
}
class Knapsack(items,theValue,weight,available) {
shared Item[] items;
shared Float theValue;
shared Integer weight;
shared Integer available;
shared Boolean canAccept(Item item)
=> item.weight <= available;
String itemsString = items.fold("")((total, remaining) => "``total``\t\n``remaining.string``" );
shared actual String string = "Total value: ``theValue``\nTotal weight: ``weight``\nItems:\n``itemsString``";
}
Knapsack empty(Integer capacity)
=> Knapsack([], 0.0, 0, capacity);
Item[] items =
[
Item("map", 9, 150.0),
Item("compass", 13, 35.0),
Item("water", 153, 200.0),
Item("sandwich", 50, 160.0),
Item("glucose", 15, 60.0),
Item("tin", 68, 45.0),
Item("banana", 27, 60.0),
Item("apple", 39, 40.0),
Item("cheese", 23, 30.0),
Item("beer", 52, 10.0),
Item("cream", 11, 70.0),
Item("camera", 32, 30.0),
Item("tshirt", 24, 15.0),
Item("trousers", 48, 10.0),
Item("umbrella", 73, 40.0),
Item("trousers", 42, 70.0),
Item("overclothes", 43, 75.0),
Item("notecase", 22, 80.0),
Item("sunglasses", 7, 20.0),
Item("towel", 18, 12.0),
Item("socks", 4, 50.0),
Item("book", 30, 10.0)
];
Knapsack add(Item item, Knapsack knapsack)
=> Knapsack { items = knapsack.items.withTrailing(item);
theValue = knapsack.theValue + item.theValue;
weight = knapsack.weight + item.weight;
available = knapsack.available - item.weight; };
Float rating(Item item) => item.theValue / item.weight.float;
Knapsack pack(Item[] items, Knapsack knapsack)
// Sort the items by decreasing rating, that is, value divided by weight
=> let (itemsSorted =
items.group(rating)
.sort(byDecreasing((Float->[Item+] entry) => entry.key))
.map(Entry.item)
.flatMap((element) => element)
.sequence())
packRecursive(itemsSorted,knapsack);
Knapsack packRecursive(Item[] sortedItems, Knapsack knapsack)
=> if (exists firstItem=sortedItems.first, knapsack.canAccept(firstItem))
then packRecursive(sortedItems.rest, add(firstItem,knapsack))
else knapsack;

View file

@ -0,0 +1,34 @@
(require 'struct)
(require 'hash)
(require 'sql)
(define H (make-hash))
(define T (make-table (struct goodies (name poids valeur ))))
(define-syntax-rule (name i) (table-xref T i 0))
(define-syntax-rule (poids i) (table-xref T i 1))
(define-syntax-rule (valeur i) (table-xref T i 2))
;; make an unique hash-key from (i rest)
(define (t-idx i r) (string-append i "|" r))
;; retrieve best score for item i, remaining r availbble weight
(define (t-get i r) (or (hash-ref H (t-idx i r)) 0))
;; compute best score (i), assuming best (i-1 rest) is known
(define (score i restant)
(if (< i 0) 0
(hash-ref! H (t-idx i restant)
(if ( >= restant (poids i))
(max
(score (1- i) restant)
(+ (score (1- i) (- restant (poids i))) (valeur i)))
(score (1- i) restant)))))
;; compute best scores, starting from last item
(define (task W)
(define restant W)
(define N (1- (table-count T)))
(writeln 'total-value (score N W))
(for/list ((i (in-range N -1 -1)))
#:continue (= (t-get i restant) (t-get (1- i) restant))
(set! restant (- restant (poids i)))
(name i)))

View file

@ -0,0 +1,20 @@
;; init table
(define goodies
'((map 9 150) ; 9 is weight, 150 is value
(compass 13 35) (water 153 200) (sandwich 50 160)
(glucose 15 60) (tin 68 45)(banana 27 60) (apple 39 40)
(fromage 23 30) (beer 52 10) (🌞-suntan-cream 11 70) (camera 32 30)
(T-shirt 24 15) (pantalons 48 10) (umbrella 73 40)
(☔️-trousers 42 70) (☔️-overclothes 43 75) (note-case 22 80)
(🌞-sun-glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10)))
(list->table goodies T)
(task 400)
total-value 1030
→ (socks 🌞-sun-glasses note-case ☔️-overclothes ☔️-trousers 🌞-suntan-cream banana
glucose sandwich water compass map)
(length (hash-keys H))
→ 4939 ;; number of entries "i | weight" in hash table

View file

@ -0,0 +1,153 @@
output file "Knapsack Problem Solution"
include "ConsoleWindow"
def tab 20
_numberOfObjects = 21
_weightOfKnapsack = 400
dim as short n : n = _numberOfObjects /* The number of objects available to pack */
dim as Str31 s(_numberOfObjects) /* The names of available objects */
dim as short c(_numberOfObjects) /* The *COST* of the ith object i.e. how much weight you must carry to pack the object */
dim as short v(_numberOfObjects) /* The *VALUE* of the ith object i.e. on a scale of 1 to 200, how important is it that the object included */
dim as short W : W = _weightOfKnapsack /* The maximum weight your knapsack will carry in ounces*/
s(0) = "map"
s(1) = "compass"
s(2) = "water"
s(3) = "sandwich"
s(4) = "glucose"
s(5) = "tin"
s(6) = "banana"
s(7) = "apple"
s(8) = "cheese"
s(9) = "beer"
s(10) = "suntan cream"
s(11) = "camera"
s(12) = "T-shirt"
s(13) = "trousers"
s(14) = "umbrella"
s(15) = "waterproof pants"
s(16) = "raincoat"
s(17) = "note-case"
s(18) = "sunglasses"
s(19) = "towel"
s(20) = "socks"
s(21) = "socks"
c(0) = 9
c(1) = 13
c(2) = 153
c(3) = 50
c(4) = 15
c(5) = 68
c(6) = 27
c(7) = 39
c(8) = 23
c(9) = 52
c(10) = 11
c(11) = 32
c(12) = 24
c(13) = 48
c(14) = 73
c(15) = 42
c(16) = 43
c(17) = 22
c(18) = 7
c(19) = 18
c(20) = 4
c(21) = 30
v(0) = 150
v(1) = 35
v(2) = 200
v(3) = 160
v(4) = 60
v(5) = 45
v(6) = 60
v(7) = 40
v(8) = 30
v(9) = 10
v(10) = 70
v(11) = 30
v(12) = 15
v(13) = 10
v(14) = 40
v(15) = 70
v(16) = 75
v(17) = 80
v(18) = 20
v(19) = 12
v(20) = 50
v(21) = 10
local fn FillKnapsack
dim as short cur_w
dim as double tot_v : tot_v = 0
dim as short i, maxi, finalWeight : finalWeight = 0
dim as short finalValue : finalValue = 0
dim as short used(_numberOfObjects)
for i = 0 to n
used(i) = 0
next
cur_w = W
while cur_w > -1
maxi = -1
BeginCCode
for ( i = 0; i < n; ++i)
if ((used[i] == 0) && ((maxi == -1) || ((float)v[i]/c[i] > (float)v[maxi]/c[maxi])))
maxi = i;
EndC
used(maxi) = 1
cur_w -= c(maxi)
tot_v += v(maxi)
if (cur_w >= 0)
print s(maxi), c(maxi), v(maxi)
finalWeight = finalWeight + c(maxi)
finalValue = finalValue + v(maxi)
else
print
print "Add"; int( ( (double)cur_w/c(maxi) * 100 ) +100 ); "% more of "; s(maxi); " into the knapsack to fill remaining space."
tot_v -= v(maxi)
tot_v += (1 + (double )cur_w/c(maxi)) * v(maxi)
end if
wend
print
print "Filled the bag with objects whose total value is"; finalValue; "."
print "Total weight of packed objects is"; finalWeight; " ounces."
end fn
dim as short i, totalValue, totalWeight
print
print "Available Items", "Weight in ounces", "Value (Scale of 1 to 200)"
for i = 0 to _numberOfObjects
print s(i), c(i), v(i)
totalValue += v(i)
totalWeight += c(i)
next
print
print "Total capacity of knapsack:"; W; " ounces"; "."
print "Total value of all"; _numberOfObjects; " objects:"; totalValue; "."
print "Total weight of all"; _numberOfObjects; " objects:"; totalWeight; " ounces."
print
print
print "Most optimal packing considering weight and value:"
print
print "Item", "Weight", "Value"
fn FillKnapsack

View file

@ -0,0 +1,70 @@
var raw = <<'TABLE'
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
suntancream, 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
TABLE
struct KnapsackItem {
String name,
Number weight,
Number value,
}
var items = []
raw.each_line{ |row|
var fields = row.split(/\s*,\s*/)
items << KnapsackItem(
name: fields[0],
weight: fields[1].to_n,
value: fields[2].to_n,
)
}
var max_weight = 400
var p = [
items.len.of { [[0, []], max_weight.of(nil)...] }...,
max_weight.inc.of {[0, []]}
]
func optimal(i, w) {
if (!defined p[i][w]) {
var item = items[i];
if (item.weight > w) {
p[i][w] = optimal(i.dec, w)
}
else {
var x = optimal(i.dec, w)
var y = optimal(i.dec, w - item.weight)
if (x[0] > (y[0] + item.value)) {
p[i][w] = x;
}
else {
p[i][w] = [y[0] + item.value, [y[1]..., item.name]]
}
}
}
return p[i][w]
}
var sol = optimal(items.end, max_weight)
say "#{sol[0]}: #{sol[1]}"

View file

@ -0,0 +1,25 @@
# 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
# detail.
def dynamic_knapsack(W):
. as $objects
| length as $n
| reduce range(1; $n+1) as $i # i is the number of items
# state: m[i][j] is an array of [value, array_of_object_names]
(null; # see above remark about initialization of m
$objects[$i-1] as $o
| reduce range(0; W+1) as $j
( .;
if $o.weight <= $j then
.[$i-1][$j][0] as $v1 # option 1: do not add this object
| (.[$i-1][$j - $o.weight][0] + $o.value) as $v2 # option 2: add it
| (if $v1 > $v2 then
[$v1, .[$i-1][$j][1]] # do not add this object
else [$v2, .[$i-1][$j - $o.weight][1]+[$o.name]] # add it
end) as $mx
| .[$i][$j] = $mx
else
.[$i][$j] = .[$i-1][$j]
end))
| .[$n][W];

View file

@ -0,0 +1,26 @@
def objects: [
{name: "map", "weight": 9, "value": 150},
{name: "compass", "weight": 13, "value": 35},
{name: "water", "weight": 153, "value": 200},
{name: "sandwich", "weight": 50, "value": 160},
{name: "glucose", "weight": 15, "value": 60},
{name: "tin", "weight": 68, "value": 45},
{name: "banana", "weight": 27, "value": 60},
{name: "apple", "weight": 39, "value": 40},
{name: "cheese", "weight": 23, "value": 30},
{name: "beer", "weight": 52, "value": 10},
{name: "suntancream", "weight": 11, "value": 70},
{name: "camera", "weight": 32, "value": 30},
{name: "T-shirt", "weight": 24, "value": 15},
{name: "trousers", "weight": 48, "value": 10},
{name: "umbrella", "weight": 73, "value": 40},
{name: "waterproof trousers", "weight": 42, "value": 70},
{name: "waterproof overclothes", "weight": 43, "value": 75},
{name: "note-case", "weight": 22, "value": 80},
{name: "sunglasses", "weight": 7, "value": 20},
{name: "towel", "weight": 18, "value": 12},
{name: "socks", "weight": 4, "value": 50},
{name: "book", "weight": 30, "value": 10}
];
objects | dynamic_knapsack(400)[]

View file

@ -0,0 +1,3 @@
$jq -M -c -n -f knapsack.jq
1030
["map","compass","water","sandwich","glucose","banana","suntancream","waterproof trousers","waterproof overclothes","note-case","sunglasses","socks"]