# Random Number Within Range But Excluding

Hey all, I want to write a function that will generate a random number, but I want to exclude the last number generated… ie: A random number from 1 to 10 but it cannot be 8… I know how to get a random number between 1 and 10, but how do I exclude 8 without asking later if the number is equal to 8?

``````
on rnd()

set randomNumber to (random number from 1 to 10) as integer

return randomNumber

end rnd

``````

Hi,

something like this. It passes the last number as parameter

``````
property randomNumber : 0

set randomNumber to rnd(randomNumber)

on rnd(lastNumber)
repeat
set rndNumber to (random number from 1 to 10)
if rndNumber is not lastNumber then return rndNumber
end repeat
end rnd

``````

Perhaps

``````global lastRnd
set lastRnd to 0

on rnd()
set minVal to 1
set maxVal to 10
if lastRnd â‰  0 then
set maxVal to maxVal - minVal - 2
set minVal to 0
end if

set randomNumber to (random number from minVal to maxVal) as integer
set lastRnd to ((randomNumber + lastRnd) mod 10) + 1
return lastRnd
end rnd

``````

Edited to allow for result ranges beginning with other than 1

Here is my deterministic runtime version:

``````to make_randomSourceWithNoRepeats(lo, hi)
-- NOTE: By definition, this is less "random" than the even the normal, poor, pseudo random source.
script
property lastValue : missing value
to rnd()
set high to hi
if lastValue is not missing value then
-- reduce the range
set high to high - 1
end if
set randomValue to random number from lo to high
if lastValue is not missing value then
-- adjust the value selected from the reduced range to avoid the previous value
if randomValue â‰¥ lastValue then
set randomValue to randomValue + 1
end if
end if
set lastValue to randomValue
return randomValue
end rnd
end script
end make_randomSourceWithNoRepeats

set r to make_randomSourceWithNoRepeats(1, 10)
set l to {}
repeat 100 times
set end of l to r's rnd()
end repeat
l

``````

oh, ok, thanks!