1.

Solve : Help with rearranging digits?

Answer»

I read about a math FORMULA and I'm making a batch file to work through it.
This requires a 4 digit number to be rearranged from highest to lowest, for example: it would change 7263 to 7632.
I would also need it to change it to lowest to highest (7263 to 2367.)

So the code would be:
Code: [Select]@echo off
title Kaprekar's Constant
echo.
echo.
echo Enter a 4 digit number
set /p num1=
set num2=6175
echo.
echo You entered %num1%
cls
set num6=0
echo.
:ent
echo.
echo Rearranging DIGITS...

REM This is where it would rearrange the digits in num1 so they are highest to lowest.
REM num3 would equal the above
REM This is where it would rearrange the digits in num1 so they are lowest to highest.
REM num4 would equal the above

echo %num3%-%num4%
set /a num5=%num3%-%num4%
echo =%num5%
set /a num6=%num6%+1
if %num5%==%num2% goto end
goto ent
:end
echo.
echo.
echo %num1% was transformed into %num2%.
echo It took %num6% STEPS to calculate.
echo.
echo Press any key to exit...
pause>nul
if you are only using 4 digits I would first seporate them into their own string using %num1:~0,1% ; %num~:~1,1% ; %num:~2,1% ; %num1:~3,1%

Then you use the if ___ GTR ____ set num#=__________ a BUNCH to find the correct order.And you really only need to get the numbers sorted high to low or low to high. After that you can just use string parsing like you were just shown by lemon to reverse the number.

I suppose you could create your own bubble sort algorithm but we could also K.I.S.S.
As you are parsing the 4 digit number into individual digits you could echo each individual digit to a temp file. Then in a FOR loop you could use the sort command to read back the file in sorted order and assign it to a new variable.



Discussion

No Comment Found