aboutsummaryrefslogtreecommitdiff
path: root/challenge-197/roger-bell-west/lua/ch-2.lua
blob: 6ffc9648b755607168945b6eeaca0a0018dfa83d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#! /usr/bin/lua

function is_wigglesorted(l)
   for i = 1, #l-1 do
      if i % 2 == 1 then
         if l[i] >= l[i+1] then
            return false
         end
      else
         if l[i] <= l[i+1] then
            return false
         end
      end
   end
   return true
end

function wigglesort(l)
   local s = l
   table.sort(s)
   local le = #s
   local p = math.floor(le / 2)
   local a = {}
   local b = {}
   for ii, v in ipairs(s) do
      if ii < p  then
         table.insert(a, v)
      else
         table.insert(b, v)
      end
   end
   local i = 1
   local o = {}
   if le % 2 == 1 then
      table.insert(o, table.remove(b, 1))
      i = 2
   end
   for j = i, #s do
      if j % 2 == 1 then
         table.insert(o, table.remove(a))
      else
         table.insert(o, table.remove(b))
      end
   end
   return o      
end


if not is_wigglesorted({1,5,1,1,6,4}) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if is_wigglesorted({1,6,1,5,1,4}) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if not is_wigglesorted({1,3,2,2,3,1}) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if is_wigglesorted({2,3,1,3,1,2}) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if not is_wigglesorted({1,3,2,2,3,1}) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if is_wigglesorted(wigglesort({1,5,1,1,6,4})) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if is_wigglesorted(wigglesort({1,3,2,2,3,1})) then
   io.write("Pass")
else
   io.write("FAIL")
end
io.write(" ")

if is_wigglesorted(wigglesort({1,3,2,2,2,3,1})) then
   io.write("Pass")
else
   io.write("FAIL")
end
print("")