1+ -- Tests for cocktail_sort.lua
2+ local cocktail_sort = require ' cocktail_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+ -- Wrap for Lua's table sort so that it returns
21+ -- the passed-in table
22+ local function sort (t , comp )
23+ table.sort (t , comp )
24+ return t
25+ end
26+
27+ -- Returns a copy of a an array
28+ local function clone (t )
29+ local _t = {}
30+ for k ,v in ipairs (t ) do _t [k ] = v end
31+ return _t
32+ end
33+
34+ -- Checks if t1 and t2 arrays are the same
35+ local function same (t1 , t2 )
36+ for k ,v in ipairs (t1 ) do
37+ if t2 [k ] ~= v then return false end
38+ end
39+ return true
40+ end
41+
42+ -- Generates an array of n values in random order
43+ local function gen (n )
44+ local t = {}
45+ for i = 1 , n do t [i ] = math.random (n ) end
46+ return t
47+ end
48+
49+ -- Note: Let's add a bit of randomness
50+ math.randomseed (os.time ())
51+
52+ run (' Empty arrays' , function ()
53+ local t = {}
54+ assert (same (sort (clone (t )),cocktail_sort (t )))
55+ end )
56+
57+ run (' Sorted array' , function ()
58+ local t = {1 , 2 , 3 , 4 , 5 }
59+ assert (same (sort (clone (t )),cocktail_sort (t )))
60+ end )
61+
62+ run (' Array sorted in reverse' , function ()
63+ local t = {5 , 4 , 3 , 2 , 1 }
64+ assert (same (sort (clone (t )),cocktail_sort (t )))
65+ local t = {5 , 4 , 3 , 2 , 1 }
66+ local comp = function (a ,b ) return a > b end
67+ assert (same (sort (clone (t ), comp ),cocktail_sort (t , comp )))
68+ end )
69+
70+ run (' Array containing multiple occurences of the same value' , function ()
71+ local t = {4 , 4 , 8 , 2 , 2 }
72+ local comp = function (a ,b ) return a <= b end
73+ assert (same (sort (clone (t )),cocktail_sort (t , comp )))
74+ local t = {0 , 0 , 0 , 0 , 0 }
75+ local comp = function (a ,b ) return a <= b end
76+ assert (same (sort (clone (t )),cocktail_sort (t , comp )))
77+ end )
78+
79+ run (' Large array of random values (1e3 values)' , function ()
80+ local t = gen (1e3 )
81+ local comp = function (a ,b ) return a <= b end
82+ assert (same (sort (clone (t )),cocktail_sort (t , comp )))
83+ end )
84+
85+ print ((' -' ):rep (80 ))
86+ print ((' Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%' )
87+ :format (total , pass , total - pass , (pass * 100 / total )))
0 commit comments