[EDIT] I solved it ... kind of... I've added boolean variable that is set to true if range was set. Now I can add whole output to stringlist and delete duplicates... but there is still problem with last range not being found...
procedure TForm1.btnGOClick(Sender: TObject);
var
lowC, highC, tmpLow, tmpHigh, x,i,lastindex: integer;
ResRange:string;
rfound: Boolean;
begin
rfound:=false;
target.lines.clear;
lastIndex:=0;
X:=0;
for i := 0 to source.lines.count-1 do
Begin
lowC := StrToInt(Source.Lines.Strings[i]);
HighC := StrToInt(Source.Lines.Strings[i+1]);
X:=i;
if lowc+1=highc then
Begin
tmpLow := lowC;
X:=i;
While StrToInt(Source.Lines.Strings[X])+1 = StrToInt(Source.Lines.Strings[X+1]) do
Begin
tmpHigh := StrToInt(Source.Lines.Strings[X+1]);
Inc(X);
end;
if rfound=false then begin
ResRange := tmpLow.ToString+'-'+tmpHigh.ToString;
rfound:=true;
end;
end
else
Begin
rfound:=false;
if lowC<>tmpHigh then
begin
ResRange := Lowc.ToString;
end else ResRange := tmpLow.ToString+'-'+tmpHigh.ToString;
Target.lines.Add(resRange);
end;
end;
end;
-------------------------------------
Today I met with this situation at my work. My co-worker had this list (of folders). Well it was much longer but for purpose of this subject let say it was sth like this
1001
1005
1007
1008
1013
1014
1015
1017
1023
1029
1031
1032
1037
1038
1039
1040
He needed to quickly write it in form of ranges like this
1001
1005
1007-1008
1013-1015
1017
1023
1029
1031-1032
So I thought I could help him.
I made this but it... well it doesn't work so good. I have few problems.
I get this output :
1001
1005
1007-1008
1007-1008
1013-1015
1014-1015
1014-1015
1017
1023
1029
1031-1032
1031-1032
As You can see some values are repeated unnecessary after range has been set and last range is not present :S
Here is my code Source and Target are TMemo.
procedure TForm1.btnGOClick(Sender: TObject);
var
lowC, highC, tmpLow, tmpHigh, x,i,lastindex: integer;
ResRange:string;
begin
target.lines.clear;
lastIndex:=0;
X:=0;
for i := 0 to source.lines.count-1 do
Begin
lowC := StrToInt(Source.Lines.Strings[i]);
HighC := StrToInt(Source.Lines.Strings[i+1]);
if lowc+1=highc then
Begin
tmpLow := lowC;
X:=i;
While StrToInt(Source.Lines.Strings[X])+1 = StrToInt(Source.Lines.Strings[X+1]) do
Begin
tmpHigh := StrToInt(Source.Lines.Strings[X+1]);
Inc(X);
end;
ResRange := tmpLow.ToString+'-'+tmpHigh.ToString;
end
else
Begin
if lowC<>tmpHigh then
ResRange := Lowc.ToString;
end;
if resRange<>'' then
Target.lines.Add(resRange);
end;
end;