Batch file to delete half the lines of a text file at random?

前端 未结 6 383
囚心锁ツ
囚心锁ツ 2021-01-29 11:27

I need a way to use batch to look at every line of a text file, and delete half of the lines in that text file, choosing which lines to delete at random.

This is to simu

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-29 12:13

    The design specified in the question is flawed. You cannot randomly delete half the lines because then for any given game, you might end up with 2 winners, or no winners. The input file must have a structure that specifies which contestants play each other, and then a winner must be randomly selected from each contest.

    The solution below assumes each line represents a player, and for each round, line 1 plays line 2, line 3 plays line 4, etc. The number of lines must always be a power of 2 >=2 (2, 4, 8, 16, 32, 64, ...)

    @echo off
    setlocal enableDelayedExpansion
    set "file=tournament.txt"
    for /f %%C in ('find /c /v "" ^<"%file%"') do (
      for /l %%N in (1 2 %%C) do (
        set /p "p1="
        set /p "p2="
        set /a "1/(!random!%%2)" 2>nul&&echo !p1!||echo !p2!
      )
    ) <"%file%" >"%file%.new"
    move /y "%file%.new" "%file%" >nul
    

    The outer loop counts the number of lines. The inner loop counts the odd numbers from 1 to the count, so it iterates exactly (line count divided by 2) times. The inner loop has input redirected to the source file, and the output redirected to a temporary file.

    Each inner loop iteration represents a game in the tournament. SET /P is used to load the player names into variables. Then 1 is divided by a random number modulo 2, which will result in a divide by 0 error 50% of the time. The error message is redirected to nul, and then conditional operators are used to print one or the other player to the output file.

    Upon completion of the loop, the temporary file is moved to replace the original file.

提交回复
热议问题