|
| 1 | +-- Tests for knapsack.lua |
| 2 | +local knapsack = require 'knapsack' |
| 3 | + |
| 4 | +local total, pass = 0, 0 |
| 5 | + |
| 6 | +local function dec(str, len) |
| 7 | + return #str < len |
| 8 | + and str .. (('.'):rep(len-#str)) |
| 9 | + or str:sub(1,len) |
| 10 | +end |
| 11 | + |
| 12 | +local function run(message, f) |
| 13 | + total = total + 1 |
| 14 | + local ok, err = pcall(f) |
| 15 | + if ok then pass = pass + 1 end |
| 16 | + local status = ok and 'PASSED' or 'FAILED' |
| 17 | + print(('%02d. %68s: %s'):format(total, dec(message,68), status)) |
| 18 | +end |
| 19 | + |
| 20 | +-- Fuzzy equality test |
| 21 | +local function fuzzyEq(a,b) return math.abs(a-b) < 1e-2 end |
| 22 | + |
| 23 | +run('Testing fractional knapsack', function() |
| 24 | + local items = { |
| 25 | + {name = 'Apple', w = 3, b = 5}, |
| 26 | + {name = 'Orange', w = 4, b = 5}, |
| 27 | + {name = 'Salt', w = 2, b = 3}, |
| 28 | + {name = 'Pepper', w = 1, b = 2}, |
| 29 | + {name = 'Rice', w = 5, b = 6}, |
| 30 | + } |
| 31 | + local capacity = 10 |
| 32 | + local sack = knapsack.fractional(items, capacity) |
| 33 | + assert(#sack == 3) |
| 34 | + local s1, s2, s3 = sack[1], sack[2], sack[3] |
| 35 | + print('s3', s3.w-1) |
| 36 | + assert(s1.name == 'Rice' and s1.p == 1 and s1.w == 5 and s1.b == 6) |
| 37 | + assert(s2.name == 'Orange' and s2.p == 1 and s2.w == 4 and s2.b == 5) |
| 38 | + assert(s3.name == 'Apple' and fuzzyEq(s3.p,0.33) and s3.w == 1 and fuzzyEq(s3.b,1.67)) |
| 39 | +end) |
| 40 | + |
| 41 | + |
| 42 | +print(('-'):rep(80)) |
| 43 | +print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') |
| 44 | + :format(total, pass, total-pass, (pass*100/total))) |
0 commit comments