Отброшу сейчас рассмотрение типа данных (приведу пример StringGrid для наглядности) - можно использовать динамические массивы, а также будем считать последовательности упорядоченными. Тогда я бы делал один цикл, но в нём прогонял 2 индекса массивов (даже три, если учитывать массив результата) параллельно.
Код:
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
bEnd: Boolean = false;
i: Integer = 1;
j: Integer = 1;
k: Integer = 1;
A, B: Integer;
maxI: Integer = 4;
maxj: Integer = 3;
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.Cells[1,1]:= '23';
StringGrid1.Cells[1,2]:= '25';
StringGrid1.Cells[1,3]:= '36';
StringGrid1.Cells[1,4]:= '45';
StringGrid1.Cells[2,1]:= '18';
StringGrid1.Cells[2,2]:= '20';
StringGrid1.Cells[2,3]:= '31';
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
while not bEnd do
begin
A:= StrToInt(StringGrid1.Cells[1, i]);
B:= StrToInt(StringGrid1.Cells[2, j]);
if (Abs(A - B) <= 5) then
begin // i++, j++, k++
StringGrid1.Cells[3, k]:= IntToStr(A);
StringGrid1.Cells[4, k]:= IntToStr(B);
Inc(k);
if (i = maxI) or (j = maxJ) then
bEnd:= true
else
begin
Inc(i); Inc(j);
end
end
else if (A < B) then
begin // i++
if i = maxI then
bEnd:= true
else
Inc(i);
end
else
begin // j++
if j = maxJ then
bEnd:= true
else
Inc(j);
end;
end;
end;
end.