9 years
edited 8 years
This snippet is a replacement to the BJ function GetRandomSubGroup with the advantage of being able to directly enumerate random number of units in a group instead of creating another subgroup of an already existing group. Notice that this is not the same as GroupEnumUnitsInRangeCounted in which case the enumerated units are not random but is based on which units are picked first.
1 library RandomIteration2 3 globals4 private group tempGroup = CreateGroup()
5 private integer unitCount
6 endglobals7 8 private function EnumUnits takes nothing returns boolean
9 call GroupAddUnit(tempGroup, GetFilterUnit())
10 set unitCount = unitCount + 1
11 return false
12 endfunction13 14 function EnumRandomUnitsInRangeCounted takes group g, real x, real y, real radius, integer limit returns nothing
15 local real chance
16 local unit u
17 call GroupEnumUnitsInRange(g, x, y, radius, Filter(function EnumUnits))
18 set chance = I2R(limit)/I2R(unitCount)
19 loop20 set u = FirstOfGroup(tempGroup)
21 exitwhen u == null or limit == 0
22 call GroupRemoveUnit(tempGroup, u)
23 if GetRandomReal(0, 1) <= chance then
24 call GroupAddUnit(g, u)
25 set limit = limit - 1
26 endif27 endloop28 set u = null
29 endfunction30 31 function EnumRandomUnitsInRectCounted takes group g, rect r, integer limit returns nothing
32 local real chance
33 local unit u
34 call GroupEnumUnitsInRect(g, r, Filter(function EnumUnits))
35 set chance = I2R(limit)/I2R(unitCount)
36 loop37 set u = FirstOfGroup(tempGroup)
38 exitwhen u == null or limit == 0
39 call GroupRemoveUnit(tempGroup, u)
40 if GetRandomReal(0, 1) <= chance then
41 call GroupAddUnit(g, u)
42 set limit = limit - 1
43 endif44 endloop45 set u = null
46 endfunction47 48 endlibrary