I want to make a list of numbers within a range that are randomly arranged and do not repeat any previously used number from the range.
I’ve tried a variety of things but have not gotten the results I desire.
I searched and didn’t quite find what I’m looking for.
http://macscripter.net/viewtopic.php?id=31549
The 2nd to last post here looked promising but didn’t yield the results I’m looking for.
This of course does not work at all…
set theList to {}
repeat with t from 1 to 10
set wig to ""
copy wig to the end of theList
end repeat
repeat with t from 1 to 10
set item (random number from 1 to 10) to t
end repeat
the desired result would be something like
theList → {3,5,6,7,4,1,9,8,2,10}
Any help would be appreciated
Hi,
simple solution
property maxValue : 10
set theList to {}
repeat until (count theList) = maxValue
set r to (random number from 1 to maxValue)
if theList does not contain {r} then set end of theList to r
end repeat
Thank you! That was what I was trying to get but I just couldn’t wrap my head around it.
Or this:
set maxValue to 10
set theSource to {}
repeat with i from 1 to maxValue
set end of theSource to i
end repeat
set theList to {}
repeat maxValue times
set r to some number of theSource
set end of theList to r
set item r of theSource to missing value
end repeat
theList
Nigel’s solution is also very common for shuffling in cards in card games. Also it looks more code but in reality it contains less overhead.
Less overhead primarily because it doesn’t do the “list does not contain” test.
And doesn’t have to keep doing it until the random process delivers an unused number (or, at the end of the list, the unused number).
Nigel mentioned it too but I was keeping a counter and I had sometime above 60 repeats and almost never below 20 while Nigels is 20 loops; this what I mentioned with overhead.
Just for the sake of it, here’s an extension which allows both minimum and maximum values to be passed. As the handler’s labelled parameters look a little like one of AppleScript’s range references, I’ve imitated the references by making it immaterial which end of the range is which. Unlike range references, though, labelled parameters themselves can be given in any order, so you can have fun trying to confuse other scripters. 
on randomiseIntegers from minValue to maxValue
-- Integer checks here.
if (minValue > maxValue) then set {minValue, maxValue} to {maxValue, minValue}
set theSource to {}
repeat with i from minValue to maxValue
set end of theSource to i
end repeat
set theList to {}
set baseValue to minValue - 1 -- To save +1s in the repeat!
repeat maxValue - baseValue times
set r to some number of theSource
set end of theList to r
set item (r - baseValue) of theSource to missing value
end repeat
return theList
end randomiseIntegers
randomiseIntegers from -5 to 5
-- Or: randomiseIntegers from 5 to -5
-- Or: randomiseIntegers to 5 from -5
-- Or: randomiseIntegers to -5 from 5