Forum

> > CS2D > Scripts > How to take one of each in a table?
ForenübersichtCS2D-Übersicht Scripts-ÜbersichtEinloggen, um zu antworten

Englisch How to take one of each in a table?

22 Antworten
Seite
Zum Anfang Vorherige 1 2 Nächste Zum Anfang

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

Vehk
User Off Offline

Zitieren
user 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.

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

Promaster
User Off Offline

Zitieren
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

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

Flacko
User Off Offline

Zitieren
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:
Zitat
1
1
1
1
4
4
4
4
4
5
5
5
5
1× editiert, zuletzt 14.10.17 21:49:13
Zum Anfang Vorherige 1 2 Nächste Zum Anfang
Einloggen, um zu antworten Scripts-ÜbersichtCS2D-ÜbersichtForenübersicht