Applescript, I am trying to make a list appear in a dialog box with only 3 of the total amount of items. For example, I have a list of 5 possible items, I want the dialog box to display 3 random ones, but with no repeats. I don't know if I'm on the right track or not but Im stuck.
set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"}
set r to some item of myList
set newList to (myList without r)
set t to some item of newList
set newerList to (newList without t)
newList
A different approach than vadian's. The problem with vadian's script is that in theory the script could run forever, if the script continuously picks an item it has taken before. Therefore, it's better to have a solution that doesn't have collisions. It takes a little more effort, because after each time an item has been picked, the value has to be removed from the list. Since there is no simple command to do this in AppleScript, the script has to do it "manually".
The easiest way is to create a parallel list containing the indices of the input list, pick a random index in each iteration, and set it to a non-integer value. This way we ensure that the item is picked only once.
set myList to {"Apples", "Bananas", "Oranges", "Grapes", "Turkey"}
set idxList to {}
-- first create a list with indexes
repeat with x from 1 to count myList
set end of idxList to x
end repeat
set newList to {}
repeat 3 times
-- pick a random index
set theIndex to some integer of idxList
-- add item to newlist based on picked index
set end of newList to item theIndex of myList
-- set the picked index to missing value so it will not be picked again
set item theIndex of idxList to missing value
end repeat
newList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With