Home > other >  Return Contents of Array Inside Loop with Array Number as Variable
Return Contents of Array Inside Loop with Array Number as Variable

Time:09-17

I cracking my head for over 2 hours to solve this but i still have not understand how this works.

This code suppose to go thru all PNGs inside current script folder and put into folder1 array.

Then I need to randomly generate number inside a loop and randomly pick photos from the array and return the photo file name.

Thanks in advance.

echo 
cls
setlocal enableDelayedExpansion

set /a photos=1
for %%G in (*.png) do (set folder1[!photos!]=%%~G 
set /a photos =1 )

set totaloutput=2

for /l %%x in (1, 1, %totaloutput%) do (

    set /a "_rand=(%RANDOM% * 20 /32768) 1"
    
    echo _rand is !_rand1!
    echo folder1 is "!folder1[%%_rand]!"
    echo folder1 is "!folder1[%_rand%]!"
    echo folder1 is %folder1[!_rand!]%
    
    )

Final code:

echo off
cls
setlocal enableDelayedExpansion

set /a photos=1
for %%G in (*.png) do (
    set folder1[!photos!]=%%~G
    set /a photos =1 )

set totaloutput=10

for /l %%x in (1, 1, %totaloutput%) do (
    set /a "_rand=(!RANDOM! * (%photos%-1) /32768) 1"
    
    echo _rand is !_rand!
    FOR %%G IN ("!_rand!") DO echo folder1 is "!folder1[%%~G]!"
)

Output Sample:

_rand is 2
folder1 is "b2.png"
_rand is 6
folder1 is "b6.png"
_rand is 3
folder1 is "b3.png"
_rand is 3
folder1 is "b3.png"
_rand is 5
folder1 is "b5.png"
_rand is 6
folder1 is "b6.png"
_rand is 2
folder1 is "b2.png"
_rand is 3
folder1 is "b3.png"
_rand is 3
folder1 is "b3.png"
_rand is 6
folder1 is "b6.png"

CodePudding user response:

You have a couple of problems with your code.

You need to use delayed expansion with the RANDOM variable. Every iteration of the output will be the same unless you do. The random calculation should also use the count of your files otherwise you are limited to the first 20 files in your existing code. So that line should change to this.

set /a "_rand=(!RANDOM! * %photos% /32768) 1"

Because you are inside a parenthesized code block you essentially need to do two layers of expansion to get the value of the array. You have two options to do that.

CALL method

CALL echo folder1 is "%%folder1[!_rand!]%%"

FOR meta-variable.

FOR %%G IN ("!_rand!") DO echo folder1 is "!folder1[%%~G]!"

Edit: One more bug in your code. If there is one file in the directory your file count will be two. You need to initialize the variable to zero and add one to it before you create the array variable.

set /a photos=0
for %%G in (*.png) do (
    set /a photos =1
    set folder1[!photos!]=%%~G
)
  • Related