Analysis of Teacher qzwqzw's Code on Floor 32:
Take a random number between 0-3 with the range of 0-3.
The code is modified as follows:
@echo off
setlocal EnableDelayedExpansion
:: Initialize the sequence
for /l %%i in (0,1,3) do (
set rnum%%i=%%i
)
:: Randomly swap the sequence
for /l %%i in (0,1,3) do (
set /a rnd=!random! %% 3
call set tmp=%%rnum!rnd!%%
set rnum!rnd!=!rnum%%i!
set rnum%%i=!tmp!
)
set rnum
Analyze line by line as follows:
------------------------------------------
First FOR loop (0-3), four times
Key sentence: set rnum%%i=%%i
rnum0=0
rnum1=1
rnum2=2
rnum3=3
------------------------------------------
Second FOR loop (0-3), four times
----------First time:---------
Key sentence 1: set /a rnd=!random! %% 3
Running result: rnd=1
(!random! %% 3 takes any integer between 0-3 "here it is assumed to be 1"
Function: Assign any integer between 0-3 to variable rnd )
Key sentence 2: call set tmp=%%rnum!rnd!%%
Running result: tmp=1
(Because at this time!rnd! is 1, rnum!rnd! is rnum1
At this time rnum1 is 1, so %%rnum!rnd!%% is 1, so tmp=1.
Note: rnum is not a variable, here it is just a string, combined with!rnd! to become a variable name
Function: Cooperate with key sentence 1 to assign the "value" of any variable generated by the first loop to variable tmp)
Key sentence 3: set rnum!rnd!=!rnum%%i!
Running result: rnum1=0
(Because at this time!rnd! is 1, rnum!rnd! is rnum1,
At this time%%i is 0, rnum%%i is rnum0,
At this time!rnum0! is 0, so rnum1=0
Note: At this time, the values of the variables generated in the first FOR loop are modified as follows:
rnum0=0
rnum1=0
rnum2=2
rnum3=3
Function: Cooperate with key sentence 1 to randomly extract the variable name generated in the first FOR loop and assign it the "value" of the variable generated in the first FOR loop corresponding to "the current loop number" in the second FOR loop)
Key sentence 4: set rnum%%i=!tmp!
Running result: rnum0=1
(At this time, the values of the variables generated in the first FOR loop are modified as follows:
rnum0=1
rnum1=0
rnum2=2
rnum3=3
Now it becomes clear, there is no need to look at the next 3 loops. It is exactly the comment made by the author before the second FOR loop:
Function: Cooperate with key sentences 1, 2, and 3 to randomly swap the sequence.
------------------------
When I was trying to solve the problem of the same value of %random%,
Teacher qzwqzw had already defined its "non-repeatability" at the beginning of the first loop.
The target value is not the value of %random%, %random% just plays the role of random swapping....... Alas.........
I almost spend more than 20 hours reading each code of Teacher qzwqzw,
So that I have this algorithm mechanism in my mind even when I sleep at night, the gap is so big that it is unimaginable...
[
Last edited by tghksj on 2007-1-6 at 03:57 PM ]