|
|
发表于 2011-5-21 16:57:29
|
显示全部楼层
本帖最后由 caruko 于 2011-5-21 17:07 编辑
不用CALL,不用递归的办法,应该是批处理最快的方法之一吧,比CALL 递归速度要快3倍以上吧。
但是跳出FOR还是没有好的办法,目前用CALL EXIT退出循环。
不支持重复字符,因为对字符的位置敏感,重复字符的原位置值判断麻烦。
稍作修改,在原字符前后各加一个@,以保证不会意外的替换掉字符的一部分,只要字符不带@以及特殊字符即可。
代码可以得到任意字符的一个排列的下一个排列,或者得到第N个排列,比如排列字符为abcdef,现求 abdfec 的下一个排列,只要在初始化位置值后,替换STR为abdfec,计算一次以后即得到 abecdf。
支持多字符元素的组合,如代码:
- @echo off&SETLOCAL ENABLEDELAYEDEXPANSION
- set "str=1 11 12 a ab acd"
- set time1=!time!
- for %%i in (%str%) do (
- set /a n+=1,_@%%i@=n
- set "tstr=!tstr! @%%i@"
- )
- set "str=!tstr!"
- echo,!str:@=!
- for /l %%a in (1,1,10000000) do (
- set "last="&set "flag="&set "pos=0"
- for %%b in (!str!) do (
- set /a pos+=1
- if defined last (
- set /a n1=_%%b,n2=_!last!
- if !n1! gtr !n2! set flag=!last! !pos!
- set "last=%%b"
- ) else (
- set "last=%%b"
- )
- )
- if not defined flag call :end %%a
- for /f %%b in ("!flag!") do for %%c in (!str!) do if !_%%c! gtr !_%%b! set "th=%%c"
- for /f "tokens=1,3" %%b in ("!flag! !th!") do (
- set "temp=!str:%%b=#!"
- set "temp=!temp:%%c=%%b!"
- set "str=!temp:#=%%c!"
- )
- set "ppos="&set "cut1="&set "cut2="&set "array="
- for %%b in (!str!) do (
- set /a ppos+=1
- for /f "tokens=2" %%c in ("!flag!") do (
- if !ppos! geq %%c (
- set "cut2=!cut2! %%b"
- ) else (
- set "cut1=!cut1! %%b"
- )
- )
- )
- for %%i in (!cut2!) do (
- set "array=%%i !array!"
- for %%j in (!array!) do (
- if %%i gtr %%j (
- set "array=!array:%%i=#!"
- set "array=!array:%%j=%%i!"
- set "array=!array:#=%%j!"
- )
- )
- )
- set str=!cut1! !array!
- echo,!str:@=!
- )
- :end
- echo,一共%1个排列. !time1!--^>!time!
- pause>nul&exit
复制代码 |
|