Random Selection of items from a list
Often, in VisualNEO for Windows, there is a need to make a random selection from a list of items … e.g. a list of fruits or vegetables or countries etc. … this article details how you would go about implementing this with VisualNEO Win.
In your pub’s StartUp section … code something like this …
SetVar "[myFruits]" "Apple,Banana,Cherry,Pear,Peach"
StrParse "[myFruits]" "," "[myFruitsItem]" "[myFruitsItemCount]"
If the items in your list contain a comma, you can use a different character to separate the items … e.g. a semicolon … or even a multi-character separator like @#$%.
The StrParse command will create an arrayed variable set from the (comma) separated list of items … so you will end up with variables [myFruitsItem1], [myFruitsItem2] etc. … where [myFruitsItem1] will contain the value Apple, [myFruitsItem2] will contain the value Banana and so on.
Then, when you want to get a random item from the list …
Random "[myFruitsItemCount]-1" "[RandomItemNumber]"
SetVar "[RandomItemNumber]" "[RandomItemNumber]+1"
SetVar "[NextRandomItem]" "[myFruitsItem[RandomItemNumber]]"
The Random command returns a random number between 0 and the value in the first parameter … since you want a number between 1 and the number of items in the list … you ask for a result between 0 and a number that is one less than the number of items in the list … then you add one to whatever result is returned.
You then use the number returned as the index to get the corresponding array item … so if [RandomItemNumber] was 3, then [NextRandomItem] would contain Cherry … because [myFruitsItem3] was set to this value by the StrParse command before.
If your applications need to make such random selections frequently, you can consider making up your own custom commands … so you can implement the same functionality with just 2 commands … something like …
Call "gkListToArray" "Apple,Banana,Cherry,Pear" "," "myFruitsItem"
… and …
Call "gkGetRandomListItem" "myFruitsItem" "[NextRandomItem]"
Finally, if you have lists with a lot of items … you could keep your list in a .txt file … one item per line … use something like notepad.exe to make up a file that looks like …
Apple
Banana
Cherry
Peach
… and in your pub’s StartUp section … code something like this …
FileRead "[PubDir]myFruits.txt" "All" "[myFruits]"
StrParse "[myFruits]" "[#13][#10]" "[myFruitsItem]" "[myFruitsItemCount]"
… and if you don’t need to change the contents of such lists at run time, you could also mark the file as Embedded … and replace [PubDir]myFruits.txt above with [Embedded]myFruits.txt.
Comments
Tony_Kroos
This is how to create an array and get a random array item, but not a random listbox item (as seen on picture), a bit confusing.
luishp
Sorry, it was my fault!
I have changed the header image.
Thanks!