von dp am 23.August 98 um 22:15:06:
Subject: Randomized list
Sender: owner-lingo@penworks.com
The code given before about a randomized list was right and very clean. In
some of the programming I do, I often need to get random values from a given
range. That is, I need to get the numbers one at a time. I want to be able
to call a routine any number of times (often more than the number of numbers
in the list). Further, I never want get the same number two times in a row.
Here is an object which does all that:
"RandomList" object:
property plNumbers -- list of random numbers
property pMaxNumbers -- Max number of numbers
property pLastValue
on new me, howMany
set pMaxNumbers = howMany
set pLastValue = 0
mInit(me)
return me
end new
on mInit me
-- Generate the list
set plNumbers = []
repeat with i = 1 to pMaxNumbers
addAt(plNumbers, random(i), i)
end repeat
if pLastValue > 0 then -- been here at least once
set firstValue = getAt(plNumbers, 1)
-- If the first value in the new list matches the last value in the old list,
-- must switch first value with some to some other randomized slot
if pLastValue = firstValue then
set randomLoc = random(pMaxNumbers - 1) + 1
set valueToSwitch = getAt(plNumbers, randomLoc)
setAt(plNumbers, randomLoc, pLastValue)
setAt(plNumbers, 1, valueToSwitch)
end if
end if
set pLastValue = getAt(plNumbers, pMaxNumbers) -- Save away for next time
end
on mGetNextRandom me
if count(plNumbers) = 0 then -- Time to regenerate the list
mInit(me)
end if
set retVal = getAt(plNumbers, 1) -- Take the first number in the list
deleteAt(plNumbers, 1)
return retVal
end mGetNextRandom
You can create the object like this:
global goRandom -- global Random object
set goRandom = new(script "RandomList", someNumber) -- whatever value you
need
Then anytime you want another random value, you just do this:
global goRandom
set x = mGetNextRandom(goRandom)
Enjoy
Irv
Furry Pants Productions
D. Plänitz