Forum

> > CS2D > Scripts > How to take one of each in a table?
Forums overviewCS2D overview Scripts overviewLog in to reply

English How to take one of each in a table?

22 replies
Page
To the start Previous 1 2 Next To the start

old Re: How to take one of each in a table?

Vehk
User Off Offline

Quote
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.

old Re: How to take one of each in a table?

Promaster
User Off Offline

Quote
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

old Re: How to take one of each in a table?

Flacko
User Off Offline

Quote
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

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:
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
Log in to reply Scripts overviewCS2D overviewForums overview