|
| 1 | +-- Tests for shell_sort.lua |
| 2 | +local shell_sort = require 'shell_sort' |
| 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 | +-- Comparison functions |
| 21 | +local function le(a,b) return a <= b end |
| 22 | +local function ge(a,b) return a >= b end |
| 23 | + |
| 24 | +-- Checks if list is sorted |
| 25 | +function is_sorted(list, comp) |
| 26 | + comp = comp or le |
| 27 | + for i = 2, #list do |
| 28 | + if not comp(list[i-1],list[i]) then return false end |
| 29 | + end |
| 30 | + return true |
| 31 | +end |
| 32 | + |
| 33 | +-- Generates a table of n random values |
| 34 | +local function gen(n) |
| 35 | + local t = {} |
| 36 | + for i = 1, n do t[i] = math.random(n) end |
| 37 | + return t |
| 38 | +end |
| 39 | + |
| 40 | +math.randomseed(os.time()) |
| 41 | + |
| 42 | +run('Empty arrays', function() |
| 43 | + local t = {} |
| 44 | + assert(is_sorted(shell_sort({}))) |
| 45 | +end) |
| 46 | + |
| 47 | +run('Already sorted array', function() |
| 48 | + local t = {1, 2, 3, 4, 5} |
| 49 | + assert(is_sorted(shell_sort(t))) |
| 50 | +end) |
| 51 | + |
| 52 | +run('Sorting a large array (1e3 values)', function() |
| 53 | + local t = gen(1e3) |
| 54 | + assert(is_sorted(shell_sort(t))) |
| 55 | + assert(is_sorted(shell_sort(t, ge), ge)) |
| 56 | +end) |
| 57 | + |
| 58 | +print(('-'):rep(80)) |
| 59 | +print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') |
| 60 | + :format(total, pass, total-pass, (pass*100/total))) |
0 commit comments