English How to take one of each in a table?

22 replies
Goto Page
To the start Previous 1 2 Next To the start
12.10.17 03:11:49 am
Up
Vehk
User
Offline Off
user Promaster has written:
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 am
Up
Promaster
User
Offline Off
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!
edited 1×, last 12.10.17 03:37:18 am
IMG:https://image.prntscr.com/image/X1Amtfw1T3Wf3eTKzt04Ng.png
12.10.17 11:32:14 pm
Up
Flacko
User
Offline Off
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:
Quote:
1
1
1
1
4
4
4
4
4
5
5
5
5
edited 1×, last 14.10.17 09:49:13 pm
To the start Previous 1 2 Next To the start