Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a list of 15 names and want to run a script that will output these names into a txt file in random order. Is this too tough, or even possible? Any help is appreciated.

Thanks!

share|improve this question
3  
Please give more detail; how are inputting in the name list? –  wonea Nov 18 '12 at 17:19
    
...and what OS? –  Arjan Nov 18 '12 at 19:14
add comment

1 Answer 1

The following batch file randomly rearranges and prints its parameters with a probability distribution that is almost uniform.

@echo off
setlocal enabledelayedexpansion
set i=0
for %%j in (%*) do (
    set /A i=i+1
    set name[!i!]=%%j
    set roll[!i!]=!random!
)
set length=%i%
for /L %%i in (0,1,32767) do (
    for /L %%j in (1,1,%length%) do (
        if %%i EQU !roll[%%j]! echo !name[%%j]!
    )
)

In the first loop, it assigns a random number to all parameters between zero and 32767 using the built-in variable %random%. Then, it traverses all possible 'rolls' and prints the parameters with matching assigned numbers. If multiple parameters roll the same number, they are echoed in the order they appeared as parameters.

The code is very inefficient, but compact and simple. By reducing the effective range of the random variable, the algorithm can be given a significant speed boost at the cost of increasing bias towards the first specified parameters. Or you could use a proper sorting routine, such as the one specified here.

If you want the batch file to operate on a text file instead of a list of parameters, you can traverse the input with a for-command, adding matches to a space seperated list of strings, e.g.: for /F "tokens=1 delims= " %%i in ("input.txt") do (set list=!list! %%i), then calling the algorithm with this list, e.g.: call :randomsort %list%.

Writing to an output file instead of the console can be achieved by either running the batch program as is, redirecting its output with randomsort.bat > output.txt, or by appending >> output.txt to the echo command.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.