注册 登录
编程论坛 ASP技术论坛

数组问题

anjincheng 发布于 2011-04-28 15:40, 499 次点击
老师们:
    有两数组
========================================================================
Dim A,B,Count
    Count=0
A=Array("2","4","9","10","11","16","37","38","39","49")
B=Array("3","8","9","11","15","36","37","38","39","40")
 FOR i=0 to 9
 FOR J=0 to 9
       IF A(i) - B(j) = 1 OR A(i) - B(j)= -1 THEN
       Count=Count + 1
       END IF
NEXT
NEXT
=======================================================================
//以上代码实现的是:
统计数组B中的数是数组A中的相邻数的个数
例如:
数组B中的"3"是数组A中"4"的相邻数;数组B中的"38"是数组A中"39"的相邻数等等等等......
但是,以上代码会碰到以下问题,例如:
数组B中的"38",既是数组A中"39"的相邻数,同时也是数组A中"37"的相邻数,程序会把数组B中的"38"统计为2次;
可是我想实现的是,当碰到如数组B中"38"这样的数时,只统计1次即可,怎么修改代码??感谢老师!!

8 回复
#2
dzt00012011-04-28 17:00
中途跳出循环不就行了。按你的说法,应该先FOR j=0 to 9,再FOR i=0 to 9,B中10个数在都和A组有相邻

<%
Dim A,B,Count
    Count=0
A=Array("2","4","9","10","11","16","37","38","39","49")
B=Array("3","8","9","11","15","36","37","38","39","40")
FOR j=0 to 9
FOR i=0 to 9
    IF A(i) - B(j) = 1 OR A(i) - B(j)= -1 THEN
    Count=Count + 1
    exit for
    END IF
NEXT
NEXT

Response.Write Count
%>
#3
anjincheng2011-04-29 09:17
B中10个数在A中不一定都相邻,本题取数时没注意;都是相邻的了,可现实不一定都是相邻的!!
另外:如果跳出循环,还是解决不了重复统计的可能!!
如:
B的“38”与A的“37”为相邻;虽然B的“38”与A的“39”也相邻,但B的“38”已和A的“37”统计过一次了,碰到A的“39”虽然也满足条件,但不能在累加统计了!!
怎么实现!谢谢!!
#4
dzt00012011-04-29 09:45
我的代码你有没有试过?按你的数组,得到的是10,没错啊。改了数组也可以的
#5
anjincheng2011-04-29 11:05
感谢dzt0001老师!!!测试通过!感谢!

另外还有个类似问题:
有数组:
A=Array("2","4","9","10","11","16","37","38","39","49")
求该数组“任意两个数字之间不相同正差值的总个数”怎么实现?感谢!
#6
dzt00012011-04-29 12:38
程序代码:
<%
Dim A,B,Count
    Count
=0
    B
=""
A
=Array("2","4","9","10","11","16","37","38","39","49")

FOR i=0 to 9
FOR j=0 to 9
   
'IF A(i) - B(i) = 1 OR A(i) - B(i)= -1 THEN
    'Count=Count + 1
    'END IF
    if cint(A(i))>cint(A(j)) then
        
if B="" then
            B
=cint(A(i))-cint(A(j))
        
else
            B
=B&"|"&cint(A(i))-cint(A(j))
        
end if
   
end if
NEXT
NEXT

B
=cxarraynull(B,"|")

Response.Write B




'使用方法和函数表示:
'
1、cxarraynull(cxstr1,cxstr2)函数中的两个参数:
'
cxstr1:要检测的数组变量,可以为空,或其它未知的错误数据,当为空或则为错误数据返回"nodate"。
'
cxstr2:数组的分割符号,可以为空,或为chr(13)等,自动替换输出。
function cxarraynull(cxstr1,cxstr2)
if isarray(cxstr1) then
cxarraynull
= "对不起,参数1不能为数组"
Exit Function
end if
if cxstr1 = "" or isempty(cxstr1) then
cxarraynull
= "nodate"
Exit Function
end if
ss
= split(cxstr1,cxstr2)
cxs
= cxstr2&ss(0)&cxstr2
sss
= cxs
for m = 0 to ubound(ss)
cc
= cxstr2&ss(m)&cxstr2
if instr(sss,cc)=0 then
sss
= sss&ss(m)&cxstr2
end if
next
cxarraynull
= right(sss,len(sss) - len(cxstr2))
cxarraynull
= left(cxarraynull,len(cxarraynull) - len(cxstr2))
end Function

%>

没有写完,直接输出了全部正差值。用到了一个自定义函数,去掉重复项(网上搜来的)。
你可以将B再转为数组,得到有多少个元素,还可再做一个函数进行从大到小排序。
#7
anjincheng2011-04-29 13:57
老师真用心,感谢~~
#8
anjincheng2011-04-29 14:35
太感谢了dzt0001,就是我要的结果!
但怎么将B再转为数组,我弄了很久做不出来!麻烦再提示了老师!感谢!
#9
dzt00012011-04-29 22:11
我就少写了2句,你就不会了

B=cxarraynull(B,"|")
Response.Write B&"<br />"
B=split(B,"|")
count=ubound(B)
Response.Write count
1