Human.bat
Human.bat

Reputation: 145

Batch: Checking if any variables are equal

Thanks to Aacini, I now have a way to sort variables from greatest to least.

Link: Comparing and ordering multiple numbers in batch

However, if 2 or more of my variables are the same value, they won't be sorted. I'm trying test to see if two variables in the set are equal. I tried using if statements against each variable in any combination I could think of, but that isn't very efficient and is hard to change.

Is there a way I can achieve this?

@echo off
setlocal EnableDelayedExpansion

set speed1=190
set speed2=78
set speed3=78
set speed4=23

rem Get the descending order of previous elements via "order" array
for /L %%i in (1,1,4) do (
   set /A num=1000-speed%%i
    set order!num!=%%i
 )

rem Show the elements of "speed" array in descending order
for /F "tokens=2 delims==" %%i in ('set order') do (
   echo speed%%i = !speed%%i!
)

Output will only display:

speed1 = 190
speed3 = 78
speed4 = 23

Upvotes: 0

Views: 119

Answers (2)

Aacini
Aacini

Reputation: 67216

Excuse me. I don't know if you are really interested to know if two elements have the same value, or just to fix the bug of my previous solution (that don't include the elements with the same value), so I opted for solve previous bug:

@echo off
setlocal EnableDelayedExpansion

set speed1=190
set speed2=78
set speed3=78
set speed4=23

rem Get the descending order of previous elements via "order" array
REM Insert a second index to differentiate elements with the same value
for /L %%i in (1,1,4) do (
   set /A num=1000-speed%%i
    set order[!num!][%%i]=%%i
 )

rem Show the elements of "speed" array in descending order
for /F "tokens=2 delims==" %%i in ('set order') do (
   echo speed%%i = !speed%%i!
)

Upvotes: 1

MC ND
MC ND

Reputation: 70933

@echo off
    setlocal enableextensions enabledelayedexpansion

    set speed1=190
    set speed2=78
    set speed3=78
    set speed4=23

    for /f "usebackq tokens=1,2 delims=/" %%a in (`
        cmd /q /e /c "for /f tokens^=1^,2^ delims^=^= %%c in ('set speed') do (set /a %%d + 10000000 & echo /%%c)"
        ^| sort /r
    `) do (
        set /a "value=%%a-10000000"
        echo %%b=!value!
    )

Upvotes: 0

Related Questions