高分请教一个算法,不是很难!(200分)

  • 主题发起人 flintsoft
  • 开始时间
F

flintsoft

Unregistered / Unconfirmed
GUEST, unregistred user!
有一组数据,例如:
1,2,3,4,5,8,9,10,89,90,91,92
我要得到这样的结果应该如何写程序
输出结果:
1,5 8,,10, 89,92
就是得到数字中连续数字分段的信息,希望能有代码或者思路
不要告诉我看算法书,没时间任务很紧,自己也想了几个小时实在想不出我很笨
请各位高手帮帮忙
 
var a:array [0..x] of integer;
i1,i2:integer;
i1:=a[0];
write(i1);
for i2=1 to x do begin
if a[i2]=i1+1 then inc(i1)
else begin
writeln(',',i1);
i1:=a[i2];
write(i1);
end;
end;
writeln(',',i1);
 
看看这行不行:
const data: array[0..11] of integer = (1,2,3,4,5,8,9,10,89,90,91,92);

procedure TForm1.Button1Click(Sender: TObject);
var
a, b, c, i: integer;
s: string;
begin
ListBox1.Items.Clear
// 存放结果

a := data[0];
c := a;
for i := 1 to 11 do
begin
inc(c);
b := data;
if b <> c then
begin
Dec(c);
s := IntToStr(a) + ',';
if c - a = 2 then
s := s + ',';
s := s + IntToStr(c);

ListBox1.Items.Add(s);

a := b;
c := a;
end;
end;
if a = b then
ListBox1.Items.Add(IntToStr(a))
else begin
s := IntToStr(a) + ',';
if b - a = 2 then
s := s + ',';
s := s + IntToStr(b);

ListBox1.Items.Add(s);
end;
end;
 
const
MAXLEN=255;
var
Nub:array [] of integer;
Str:string;
pPos,Count,LstNub,n:integer;
begin
Str:=Edit1.text;

Count:=0;
pPos:=Pos(",",Str);
while (pPos<>0) do
begin
Inc(Count);
SetLength(Nub,Count);
Nub[Count-1]:=StrToInt(Copy(Str,1,pPos-1));
Str=Copy(Str,pPos+1,MAXLEN);
end;
SetLength(Nub,Count+1);
Nub[Count]:=StrToInt(Str);

Str:=IntToStr(Nub[0]);
for n:=1 to Count do
if (Nub[n]<>Nub[n-1]+1) then Str:=Str+","+IntToStr(Nub[n]);

Str:=Str+","+IntToStr(Nub[Count]);
Edit2.text:=Str;
end;

我手头没有Delphi,这是凭空写的,可能会有一点小错误,你先试试,不行把错误信息贴上来,我再改改。
 
已经测试过

var
i, j, k:integer;
S :array of integer;
tmpStr:String;
begin
// tmpStr:='1,2,3,4,5,8,9,10,89,90,91,92';
tmpStr:=Edit1.Text;
j:=pos(',',tmpStr);
if j<=0 then Exit;
i:=-1;
while j>0 do begin
inc(i);
SetLength(S, i+1);
S:=StrToInt(copy(tmpStr,1,j-1));
tmpstr:=copy(tmpStr,j+1,Length(tmpStr)-j+1);
j:=pos(',',tmpStr);
end;
if trim(tmpStr)<>'' then
begin
SetLength(S, i+2);
S[i+1]:=StrToInt(tmpStr);
end;

k:=S[0];
Edit2.Text:=IntToStr(k);
for j:=1 to i+1 do
begin
if S[j]=k+1 then
begin
k:=k+1;
Continue;
end
else begin
Edit2.Text:=Edit2.Text+','+ IntToStr(k);
k:=S[j];
Edit2.Text:=Edit2.Text+' '+ IntToStr(k);
Continue;
end;
end;
Edit2.Text:=Edit2.Text+','+ IntToStr(k);
end;
 
感谢各位,这就去试试,回来就给分
 
多人接受答案了。
 
顶部