random variables

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
scienceguru1.bat
Posts: 44
Joined: 01 Jan 2011 20:54

random variables

#1 Post by scienceguru1.bat » 19 Jan 2011 20:47

i can do the %random% command, and i can set color manually, but how do you set the # of didgts in the %random% command, and how can you set random color?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

Re: random variables

#2 Post by aGerman » 20 Jan 2011 12:36

It's simple. The magic word is modulo.

Have a look at this snippet:

Code: Select all

@echo off &setlocal

:: all possible HEX digits for background and foreground color
set "digits=0123456789ABCDEF"


:loop
:: calculate two random numbers between 0 and 15 using modulo operation
set /a n1 = %random% %% 16 , n2 = %random% %% 16

:: background and foreground color should never be the same, otherwise calculate new numbers
if %n1%==%n2% goto loop

:: change the colors by picking up two single digits depending on the random numbers
setlocal enabledelayedexpansion
color !digits:~%n1%,1!!digits:~%n2%,1!
endlocal

pause

Regards
aGerman

scienceguru1.bat
Posts: 44
Joined: 01 Jan 2011 20:54

Re: random variables

#3 Post by scienceguru1.bat » 20 Jan 2011 15:55

Thanks, it works

Post Reply