0

I need to randomly select an element from an array. The array may have 1-8 elements. This article appears to be out of date - it is telling me I can do it this way, but when I try (or even just copy-paste its code) it fails, instead giving me the variable's name surrounded by %s.

SET _Array[1]=Option1
SET _Array[2]=Option2
SET _Array[3]=Option3
SET _Array[4]=Option4

SET /A _throwaway=%RANDOM%
SET /A _Index=%RANDOM% * 4 / 32768

ECHO %%_Array[%_Index%]%%

Assuming that %RANDOM% * 4 / 32768 gave 1, the above should output:

Option 1

but instead it outputs:

%_Array[1]%

I've tried several permutations, doubling the %s in different places, using a CALL, even

FOR /L %%G IN (%_Index%,8,8) DO (ECHO %_Array[%%G])

No dice.

Isaac Reefman
  • 537
  • 1
  • 8
  • 26
  • 1
    try `CALL ECHO %%_Array[%_Index%]%%` – Magoo Nov 22 '22 at 06:58
  • 1
    Or `ECHO !_Array[%_Index%]!` with Delayed Expansion Enabled. See: [arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990) – Aacini Nov 22 '22 at 07:12
  • @Magoo Apparently that's not one of the permutations I used with CALL... *hangs head in shame* – Isaac Reefman Nov 22 '22 at 07:21

0 Answers0