-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiSet.lua
More file actions
125 lines (106 loc) · 2.22 KB
/
MultiSet.lua
File metadata and controls
125 lines (106 loc) · 2.22 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
local MultiSet = {}
local Debug = require("dbg")
local mt = {}
function MultiSet.new(l, isSet)
local set = {}
isSet = isSet or false
setmetatable(set, mt)
if isSet then
for _i, v in pairs(l) do set[_i] = 1 end
else
local val = nil
for _, v in ipairs(l) do
val = set[v]
if val then
set[v] = val + 1
else
set[v] = 1
end
end
end
return set
end
function MultiSet.join(a,b)
local res = MultiSet.new{}
local tmp = nil
for _i, v in pairs(a) do
tmp = b[_i]
if tmp then
res[_i] = v + tmp
else res[_i] = v end
end
for _i, v in pairs(b) do
tmp = a[_i]
if not tmp then res[_i] = v end
end
return res
end
function MultiSet.configToString(to, tc, ts)
Debug.tableOpen = to
Debug.tableClose = tc
Debug.tableSep = ts
Debug.itemOpen = '"'
Debug.itemClose = '"'
Debug.keyOpen = '['
Debug.keyClose = ']'
end
function MultiSet.tostring(ms)
local l = {}
for _i, v in pairs(ms) do l[#l + 1] = Debug.tostring(_i) .. ":" .. v end
return Debug.tostring(l)
end
function MultiSet.print(s)
print(MultiSet.tostring(s))
end
--[[
function MultiSet.union(a,b)
local res = MultiSet.new{}
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end
function MultiSet.intersection(a,b)
local res = MultiSet.new{}
for k in pairs(a) do res[k] = b[k] end
return res
end
function MultiSet.diff(a,b)
local res = MultiSet.new{}
for k in pairs(a) do
if not b[k] then res[k] = true end
end
return res
end
function MultiSet.in(e, set)
return set[e] == true
end
function MultiSet.card(set)
local count=0
for k in pairs(set) do
count = count + 1
end
return count
end
function MultiSet.product(a, b)
local res = MultiSet.new{}
local s
for k in pairs(a) do
for j in pairs(b) do
s = {k,j}
res[s] = true
end
end
return res
end
function MultiSet.table(set)
local res = {}
for e in pairs(set) do res[#res + 1] = e end
return res
end
]]
mt.__concat = MultiSet.union
mt.__add = MultiSet.join
mt.__mul = MultiSet.product
mt.__sub = MultiSet.diff
mt.__tostring = MultiSet.tostring
return MultiSet