Thread: random()
View Single Post
06-07-13, 08:32 PM   #13
SDPhantom
A Pyroguard Emberseer
 
SDPhantom's Avatar
AddOn Author - Click to view addons
Join Date: Jul 2006
Posts: 2,325
Originally Posted by Dridzt View Post
This might be helpful, it's along the lines of what's discussed here with some code examples.

Randomizing an array
I would think it's less taxing on the system to just pick a random index rather than to shuffle the entire table.

At any rate, I think this would be a more efficient way. Instead of repeatedly calling math.random() until it returns a different number, you have it randomize to one less than the max and add one if the random number returned is greater than or equals the last number returned.
Lua Code:
  1. local RandFunc,LastMin,LastMax,LastRand=math.random;
  2. function UniqueRandom(min,max)
  3.     if not max then min,max=1,min; end--    If min given, but not max, assume 1 to X
  4.     if not max then return RandFunc(); end--    if min and max not given, just return float random
  5.     if min<max then return nil; end--   Errors if min greater than max
  6.     if min==max then return min; end--  Equal min and max return that number
  7.  
  8.     if min~=LastMin or max~=LastMax then
  9. --      Initialize our variables or reset if ranges changed
  10.         LastMin,LastMax,LastRand=min,max,RandFunc(min,max);
  11.     else
  12.         local rand=RandFunc(min,max-1);--   Decrease range max by 1
  13.         if rand>=LastRand then rand=rand+1; end--   Add 1 if rand >= last result
  14.         LastMin,LastMax,LastRand=min,max,rand;
  15.     end
  16.     return LastRand;
  17. end



Originally Posted by Rainrider View Post
Good one. Would be better if it returned 1 instead of 4. It would be a more realistic d4 roll then.
__________________
WoWInterface AddOns
"All I want is a pretty girl, a decent meal, and the right to shoot lightning at fools."
-Anders (Dragon Age: Origins - Awakening)

Last edited by SDPhantom : 06-07-13 at 08:35 PM.
  Reply With Quote