Originally Posted by Dridzt
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:
local RandFunc,LastMin,LastMax,LastRand=math.random;
function UniqueRandom(min,max)
if not max then min,max=1,min; end-- If min given, but not max, assume 1 to X
if not max then return RandFunc(); end-- if min and max not given, just return float random
if min<max then return nil; end-- Errors if min greater than max
if min==max then return min; end-- Equal min and max return that number
if min~=LastMin or max~=LastMax then
-- Initialize our variables or reset if ranges changed
LastMin,LastMax,LastRand=min,max,RandFunc(min,max);
else
local rand=RandFunc(min,max-1);-- Decrease range max by 1
if rand>=LastRand then rand=rand+1; end-- Add 1 if rand >= last result
LastMin,LastMax,LastRand=min,max,rand;
end
return LastRand;
end
Originally Posted by Rainrider
|
Good one. Would be better if it returned 1 instead of 4. It would be a more realistic d4 roll then.