I’m trying to assign a random number to a variable using:
set the_variable to random number from 1 to 50.
My problem is I want to assign 10 variables, each with their own number from 1 to 50. I.E. No 2 variables can match. What’s the easiest way to do this? would listing the numbers from 1 to 50 help?
By the way-
Set variable_one to a number from 1 to 5
Set variable_two to a number from 6 to 10... etc.
is not an option.
Thanks in advance, G
In your post you have the line,
if (randomUpper - randomLower + 1) * listLength then
This did not reduce to a boolean result. Did you use the ‘equal to or greater than’ character instead of ‘*’? If so, which makes the script work (well I might add), I think the character did not make the transfer to the web.
The following script (I believe) works for what you need. It could probably be done smoother. Here’s a slightly expanded, and more easily customisable solution that allows you to easily set the number of numbers you want to generate and the upper and lower bounds for the random number generator --it would be easy to set these via dialogs.
You can’t – put them into a list and access them as item x instead. You can see this happening in the script and in the result window. Here comes the (heavily commented, though it is fairly self-explanatory) code…
set list length to 10 -- number of numbers required
set randomLower to 1 -- lower limit of random numbers
set randomUpper to 50 -- upper limit of random numbers
if (randomUpper - randomLower + 1) * listLength then -- check we've enough potential numbers to fill list!
set myList to {} -- initialise list
repeat until (length of myList = listLength) -- repeat until required amount generated
set randomNumber to random number from randomLower to randomUpper -- generate number
if myList does not contain randomNumber then -- if number is not in list already
set myList to myList & randomNumber -- add it to the list
end if
end repeat
set myReturn to "" -- initialise return string
repeat with x from 1 to listLength -- iterate through list
set myReturn to myReturn & "var" & x & " = " & item x of myList & return -- add one line of output
end repeat
return myReturn -- send to result window, or wherever else
return "Too long a list for the available numbers" -- error report when it is impossible to generate enough
end if -- unique numbers to fill the list
it would look a lot shorter without the comments and output guff!
Hope that helps, Nigel
Yes, I did. I used >=, Script Editor changed it on syntax check to the all-in-one-character version, and I didn’t notice after the copy, paste and post which then munged it to a *
Sorry for the confusion. I plead first-time-on-this-board as a (feeble) excuse
Nigel