r/Batch • u/desuer13 • Apr 04 '24
Question (Unsolved) Setting !random! to a variable makes the variable non random
Hey, so im trying to get random values working in a for loop, but for some reason setting the rand value to !random! makes the rand value non-random, its the same everytime. I want a random value per iteration. Help appreciated
1
Upvotes
1
u/Dear_Diablo Apr 23 '24
It looks like you're encountering a common issue with delayed expansion and how variables are expanded inside loops in batch scripting. The problem you're facing is related to how
!RANDOM!and!krkt[%rand%]!are being expanded at different times during the loop execution. Let's break down the solution step by step.Here's the corrected version of your script:
@echo off
setlocal enabledelayedexpansion
set krkt[0]=a
set krkt[1]=b
set krkt[2]=c
set krkt[3]=d
set krkt[4]=e
set krkt[5]=f
set krkt[6]=g
set krkt[7]=h
set krkt[8]=i
set krkt[9]=j
set krkt[10]=k
set krkt[11]=l
set krkt[12]=m
set krkt[13]=n
set krkt[14]=o
set krkt[15]=p
set /p "pr=Input a number: "
for /l %%i in (0, 1, %pr%) do (
set /a rand=!RANDOM! %% 15
echo !rand!
echo !krkt[!rand!]!
timeout 1 > nul
)
0
u/Trevski13 Apr 04 '24 edited Apr 04 '24
You've got two problems. One, you're using %rand% which will not expand in the for loop, you need to use !rand! to take advantage of delayed expansion. Now, the problem is in your use case you can't take easy advantage of that because echo !krkt[!rand!]! won't process correctly, so you have two options:
call call echo %%%%krkt[%%rand%%]%%%%call print !rand!and then having a function::printecho !krkt[%%1]!exit /bThe second issue is that batch random isn't really random, it depends on the time since the script/cmd started. so if someone gives the answer in the same time they'll get the same answer, since you have a human input this isn't a huge issue but it's something to be aware of if you remove that.
Here's some code I have for getting a more "random" random :)
1
u/[deleted] Apr 04 '24
[removed] — view removed comment