forked from patrickschulz/openPCells
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aux.lua
110 lines (95 loc) · 1.99 KB
/
aux.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
--[[
This file is part of the openPCells project.
This module provides a collection of helper functions (not geometry-related)
--]]
local M = {}
function M.call_if_present(func, ...)
if func then
return func(...)
end
end
function M.map(t, func)
local res = {}
for k, v in pairs(t) do
res[k] = func(v)
end
return res
end
function M.concat(data, sep, pre, post, newline)
pre = pre or ""
post = post or ""
sep = sep or ", "
if newline then
sep = sep .. "\n"
end
local fun = function(str)
return string.format("%s%s%s", pre, str, post)
end
local processed = M.map(data, fun)
local tabstr = table.concat(processed, sep)
return tabstr
end
function M.find(t, crit)
for i, v in ipairs(t) do
if crit(v) then
return i, v
end
end
end
function M.shuffle(t)
for i = #t, 2, -1 do
local j = math.random(i)
t[i], t[j] = t[j], t[i]
end
return t
end
function M.gcd(a, b)
if b ~= 0 then
return M.gcd(b, a % b)
else
return a
end
end
function M.tabgcd(t)
local gcd = t[1]
for i = 1, #t do
for j = 1, #t do
if i ~= j then
gcd = math.min(gcd, M.gcd(t[i], t[j]))
end
end
end
return gcd
end
function M.sum(t)
local res = 0
for _, e in ipairs(t) do
res = res + e
end
return res
end
function M.round(num)
return num >= 0 and math.floor(num + 0.5) or math.ceil(num - 0.5)
end
function M.any_of(comp, t, ...)
for _, v in ipairs(t) do
if comp(v, ...) then
return true
end
end
return false
end
function M.all_of(comp, t, ...)
for _, v in ipairs(t) do
if not comp(v, ...) then
return false
end
end
return true
end
function M.assert_one_of(msg, key, ...)
assert(M.any_of(function(v) return v == key end, { ... }),
string.format("%s must be one of { %s }", msg, table.concat({ ... }, ", "))
)
end
return M