Hi all,
I just wanted to toss in a comment so my very first post here might be usefull
If you want to be as efficient as possible, and you are not concerned about a perfectly random distribution, you can do away with converting the float to an integer. OFP is perfectly happy with something like:
_pi = 3.14159
_n = [0,1,2,3,4] select _pi
The only thing to keep in mind is the when converting floats to array indices OFP rounds off the value, it doesn't truncate. This means the first and last elements of the array are less likely to be selected that the others unless you do some other arm waving. If you're just selecting a random speaker it doesn't really matter if the distribution is perfectly random, and with some creative thinking this could probably be used as a "feature". So, my version would look like:
; untested
_unitlist = units group player
_speaker = _unitlist select random ((count _unitlist) - 0.500001)
...
There is no need for the if statement here as the random function will never pick an out of range value; if there are N elements in the array, then the indices are 0 to N-1 and the random function will return a maximum value of N-0.500001, which will be round down to N-1 when its used as an array index.
Finally, if you do want an almost perfectly random distribution then try:
_unitlist = units group player
_i = random ((count _unitlist) - 0.000001)
_i = _i - (_i % 1)
_speaker = _unitlist select _i
Now the index value will be rounded down to values in the range 0 to N-1 as random will never return exactly N.
@THobson:
Whether steps to avoid possible failures is necessary depends on your defintions of "necessary" I guess. Is it necessary that your script _never_ fail? Or are you happy with the script possibly failing for random people at random times? Granted the likelyhood of getting an out of range value is small, it is not zero, so being anal is never a "Bad Thing".
And to tell you the truth I thought you were doing it for different reasons. 15 years of C++ programming and I totally missed that there was a change (albeit small) that you might get an out of range value!!!
I also agree with you re: the mod function (mentioned in another thread on a similar topic). It's too bad BIS didn't suppy a real mod function... and a random function that returned integer values instead of reals.