# How to take one of each in a table?

22 Antworten
Gehe zu Seite
1 2
12.10.17 03:11:49
Vehk
User
Offline
Promaster hat geschrieben:
When i am sorting a table with over 200 units in it. It will freeze the server for 1 second and then works again. Is there possible to avoid the big loop and avoid the freeze time for the server when i have over 200 units in a table?

It would help if we could see the code.
12.10.17 03:15:42
Promaster
User
Offline
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function sort(t)
local ranks = {}
local i = 1

for _, v in ipairs(t) do
if not ranks[v] then
ranks[v] = i
i = i + 1
end
end

table.sort(t, function (a, b) return ranks[a] < ranks[b] end)
return t
end

worked without lagg!
1× editiert, zuletzt 12.10.17 03:37:18
Patch 13.1! Updated. 2018-02-14
12.10.17 23:32:14
Flacko
User
Offline
Unless I'm missing something, IMO this is a typical multiset/bag problem. There's no need to store the repeated elements multiple times, you just have to count the amount of repetitions (ie: multiplicity). Here I just modified the unique() function to build the multiset

Code:
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
function multiset_new(t)
local elements = {}
local multiplicity = {}
for k,v in pairs(t) do
if not multiplicity[v] then
elements[#elements+1] = v
multiplicity[v] = 1
else
multiplicity[v] = multiplicity[v] + 1
end
end
return elements, multiplicity
end
-- iteration function for kicks
function multiset_iter(elements, multiplicity)
local i, j = 1, 0
return function()
j = j + 1
if j > multiplicity[elements[i]] then
i = i + 1
j = 1
end
return elements[i]
end
end

Usage:
Code:
1
2
3
4
elements,multiplicity = multiset_new({1,1,1,1, 4,4,4,4, 5,5,5, 4, 5})
for v in multiset_iter(elements, multiplicity) do
print(v)
end

Output:
Zitat:
1
1
1
1
4
4
4
4
4
5
5
5
5
1× editiert, zuletzt 14.10.17 21:49:13
1 2
﻿