Board logo

标题: [出题]从一组数字中找出和等于某个数的所有组合 [打印本页]

作者: moniuming     时间: 2009-9-9 09:48    标题: [出题]从一组数字中找出和等于某个数的所有组合

请用下面的代码生成一组个数不确定的数字,从这组数字中找出和等于40的所有组合,如果没有等于40的组合,请给出提示...
CODE:  [Copy to clipboard]
@echo off
setlocal enabledelayedexpansion
for /l %%a in (1 1 15) do (
   set /a t=!random!%%25+1
   if not defined _!t! set "arr=!arr!!t! "
   set _!t!=ok
)
echo.!arr!
pause

作者: qq330878338     时间: 2009-9-9 09:51
吗哟  玩这个 有意思
作者: 523066680     时间: 2009-9-9 10:31    标题: Refact

CODE:  [Copy to clipboard]
@echo off
setlocal enabledelayedexpansion
for /l %%a in (1 1 15) do (
   set /a t=!random!%%25+1
   if not defined _!t! set "arr=!arr!!t! "
   set _!t!=ok
)
echo,得出的数有 %arr%
echo,
set "str2="
for %%x in (%arr%) do (set /a a+=1,fx!a!=0 &set str2=!str2! !a!_%%x)
set /a have=0
call :func "%str2%" "0"
if %have% equ 0 (echo, 没有和为40的组合)
pause
exit

:func
set now=%~1
set /a num=%~2
if !num! equ 40 (set result=%~2 &echo,!result:~2! &set /a have=1)
if "!now: =!"=="" (goto :eof)
for %%a in (%~1) do (
  set choose=%%a
  set /a ceng+=1
  call :func "!now:*%%a=!" "%~2+!choose:*_=!"
  set now=%~1
)
goto :eof



得出的数有 6 5 12 9 2 4 19 20 13 17 7 10

6+5+12+4+13
6+5+12+17
6+5+12+7+10
6+5+9+20
6+5+9+13+7
6+5+2+4+13+10
6+5+2+20+7
6+5+2+17+10
6+5+19+10
6+12+9+2+4+7
6+12+9+13
6+12+2+20
6+12+2+13+7
6+9+2+4+19
6+9+2+13+10
6+2+19+13
6+4+20+10
6+4+13+17
6+4+13+7+10
6+17+7+10
5+12+9+4+10
5+12+2+4+17
5+12+2+4+7+10
5+12+4+19
5+12+13+10
5+9+2+4+20
5+9+2+4+13+7
5+9+2+17+7
5+9+19+7
5+2+4+19+10
5+2+20+13
12+9+2+4+13
12+9+2+17
12+9+2+7+10
12+9+19
12+2+19+7
12+4+17+7
9+2+19+10
9+4+20+7
9+4+17+10
2+4+17+7+10
4+19+17
4+19+7+10
20+13+7
13+17+10
请按任意键继续. . .

[ Last edited by 523066680 on 2009-9-9 at 11:02 ]
作者: 523066680     时间: 2009-9-9 11:32
听了moniuming
的建议 增加一个判断 如果 和已经大于40 就返回上一层。
速度快很多

CODE:  [Copy to clipboard]
@echo off
setlocal enabledelayedexpansion
for /l %%a in (1 1 15) do (
   set /a t=!random!%%25+1
   if not defined _!t! set "arr=!arr!!t! "
   set _!t!=ok
)
echo,得出的数有 %arr%
echo,
set "str2="
for %%x in (%arr%) do (set /a a+=1,fx!a!=0 &set str2=!str2! !a!_%%x)
set /a have=0
call :func "%str2%" "0"
if %have% equ 0 (echo, 没有和为40的组合)
pause
exit

:func
set now=%~1
set /a num=%~2
if %num% gtr 40 (goto :eof)
if !num! equ 40 (set result=%~2 &echo,!result:~2! &set /a have=1)
if "!now: =!"=="" (goto :eof)
for %%a in (%~1) do (
  set choose=%%a
  set /a ceng+=1
  call :func "!now:*%%a=!" "%~2+!choose:*_=!"
  set now=%~1
)
goto :eof


[ Last edited by 523066680 on 2009-9-9 at 21:24 ]
作者: moniuming     时间: 2009-9-9 11:51
没刷新,发帖后才看到4楼的回复,删......

[ Last edited by moniuming on 2009-9-9 at 11:53 ]
作者: 523066680     时间: 2009-9-30 11:26
帖子还在也……




欢迎光临 中国DOS联盟论坛 (http://cndos.fam.cx/forum/) Powered by Discuz! 2.5