Page 1 of 1

Picking Random Name From Array

Posted: Thu Feb 20, 2020 12:45 am
by Mikeywatt
Hi, i need help with trying to pick a random name out of an array
here is the code
(The comments are only their as this is revision for a computing science class and the teacher likes us to make comments)

Code: Select all

Global Var_Names, Array_Names, Loop_Count, TKeys, tRandomPick

On Mouseup
   setup_variabels
   Get_Names
   Display_Name
end Mouseup

On setup_variabels
   Put 0 into loop_count //interger
   Put Clear Into Array_Names //String Array
end setup_variabels

On Get_names
   repeat with loop = 1 to 10 //Looping the upcoming commands 10 times
      Ask "What is the names you want to enter (Enter one at a time)"
      Put it into Array_Names[loop] //Putting the 10 names into an array
      end repeat
   end Get_names


On Display_Name
   Put any line of the keys of Array_names into tRandomPick //Picking random name
   Put tRandomPick into field "Output" //Outputing the random name  
end Display_Name



The problem with this is that the output is the number of the name but not the actual name any help with making it the name which is outputed would be greatly apprciated :)

Re: Picking Random Name From Array

Posted: Thu Feb 20, 2020 8:51 am
by SparkOut
You know how to reference the elements in an array, don't you? You already did this when you made your loop to create the array of names.

Code: Select all

Put it into Array_Names[loop]
the variable 'loop' is replaced each time with the key from 1 to 10 to insert a new name.
So if you have taken a random key and put it into a variable 'tRandomPick' then you know this is a key to be used with the array 'Array_Names'. You can finish this off!

Re: Picking Random Name From Array

Posted: Thu Feb 20, 2020 9:07 am
by Mikeywatt

Code: Select all

   Put any line of the keys of Array_names into tRandomPick //Picking random name
   Put Array_Names[tRandomPick] into field "Output" //Outputing the random name  
well i can say it is working just fine now thank you :).

Re: Picking Random Name From Array

Posted: Thu Feb 20, 2020 10:51 am
by bogs
Um, you didn't say if it was important or not to not have repeated picks or not, and your picking 'any line' directly from the keys of the array itself.

One way to not get the same key each time might be to put the keys of the array into a variable instead, then pick any line from the variable and, after it is picked, delete that line from the variable so it won't be available to pick again (until your out of lines, where you can regen the list in the variable).