-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.lua
79 lines (68 loc) · 1.37 KB
/
array.lua
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
-- Copyright 2019, Mansour Moufid <[email protected]>
local array = {}
function array.copy(xs)
local ys = {}
for i, x in pairs(xs) do
if type(x) == 'table' then
ys[i] = array.copy(x)
else
ys[i] = x
end
end
return ys
end
local function sub(xs, a, b)
local ys = {}
if a < 0 then
a = a + #xs + 1
end
if b < 0 then
b = b + #xs + 1
end
for i = a, b do
ys[#ys + 1] = xs[i]
end
return ys
end
array.sub = sub
local function equal(x, y)
if type(x) ~= type(y) then
return false
end
if type(x) == 'table' then
if #x == 0 and #y == 0 then
return true
else
local a = sub(x, 2, -1)
local b = sub(y, 2, -1)
return equal(x[1], y[1]) and equal(a, b)
end
else
return x == y
end
end
array.equal = equal
function array.take(xs, n)
return sub(xs, 1, n)
end
function array.last(xs, n)
return sub(xs, -n, -1)
end
function array.reverse(xs)
local ys = {}
for i, x in ipairs(xs) do
ys[#xs + 1 - i] = x
end
return ys
end
function array.median(xs)
local ys = array.copy(xs)
table.sort(ys)
local n = #ys
if n % 2 == 0 then
return 0.5 * (ys[n / 2] + ys[n / 2 + 1])
else
return ys[(n + 1) / 2]
end
end
return array