9 years
edited 8 years
This snippet is a replacement to the BJ function [lcode=jass]GetRandomSubGroup[/lcode] 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 [lcode=jass]GroupEnumUnitsInRangeCounted[/lcode] in which case the enumerated units are not random but is based on which units are picked first.
library RandomIteration
globals
private group tempGroup = CreateGroup()
private integer unitCount
endglobals
private function EnumUnits takes nothing returns boolean
call GroupAddUnit(tempGroup, GetFilterUnit())
set unitCount = unitCount + 1
return false
endfunction
function EnumRandomUnitsInRangeCounted takes group g, real x, real y, real radius, integer limit returns nothing
local real chance
local unit u
call GroupEnumUnitsInRange(g, x, y, radius, Filter(function EnumUnits))
set chance = I2R(limit)/I2R(unitCount)
loop
set u = FirstOfGroup(tempGroup)
exitwhen u == null or limit == 0
call GroupRemoveUnit(tempGroup, u)
if GetRandomReal(0, 1) <= chance then
call GroupAddUnit(g, u)
set limit = limit - 1
endif
endloop
set u = null
endfunction
function EnumRandomUnitsInRectCounted takes group g, rect r, integer limit returns nothing
local real chance
local unit u
call GroupEnumUnitsInRect(g, r, Filter(function EnumUnits))
set chance = I2R(limit)/I2R(unitCount)
loop
set u = FirstOfGroup(tempGroup)
exitwhen u == null or limit == 0
call GroupRemoveUnit(tempGroup, u)
if GetRandomReal(0, 1) <= chance then
call GroupAddUnit(g, u)
set limit = limit - 1
endif
endloop
set u = null
endfunction
endlibrary