Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
OTChET.docx
Скачиваний:
7
Добавлен:
16.08.2019
Размер:
1.49 Mб
Скачать

3.3 Анализ результатов тестирования

В результате тестирования были найдены следующие ошибки

Тип ошибки

Количество выявленных ошибок

Вид ошибки

Ошибки ввода-вывода

5

  • Некорректный ввод данных;

  • Открытие готового файла;

  • Экспорт в файл

Ошибки определения данных

4

  • Не сочетание типов данных;

  • Присвоение типу значение компонента

Ошибки вычисления

11

  • Неправильное вычисление значения PLbas

Логические ошибки

4

Неверная интерпретация компонента «stringrid1»

Ошибки манипулирования данными

0

-

Ошибки сопряжения

0

-

4. Список литературы и интернет – ресурсов:

  1. Фаронов В.В. Delphi. Программирование на языке высокого уровня. Учебник для вузов, 2008г.

  2. Благодатских В.А.,.Волнин В.А., Поскакалов К.Ф. «Стандартизация разработки программных средств.» М., «Финансы и статистика» 2003-288с.

  3. П. Дарахвелидзе, Е. Марков, «Программирование в Delphi 7 + примеры», 2007-305 с.

  4. С.Бобровский, «Delphi 7 Учебный курс С.Бобровский», 2009-347с.

  5. НепейводаН.Н. «Стили и методы программирования»ИКИ 2005 г.http://www.intuit.ru/department/se/progstyles/14

  6. Статья Н.Н. Минаевского «Модульное программирование» http://www.intuit.ru/department/pl/prinpas/4

5. Приложения

5.1 Текстымодулей

unitInfo_unit;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, Menus, ExtCtrls;

type

TInfo = class(TForm)

Memo1: TMemo;

Button1: TButton;

RadioGroup1: TRadioGroup;

procedureFormCloseQuery(Sender: TObject; varCanClose: Boolean);

procedureFormResize(Sender: TObject);

procedure Button1Click(Sender: TObject);

procedure RadioGroup1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Info: TInfo;

implementation

{$R *.dfm}

procedure TInfo.Button1Click(Sender: TObject);

begin

info.Close;

end;

procedureTInfo.FormCloseQuery(Sender: TObject; varCanClose: Boolean);

begin

memo1.Text:='';

RadioGroup1.ItemIndex:=-1;

end;

procedureTInfo.FormResize(Sender: TObject);

begin

memo1.Height:=Info.Height - memo1.Top - 50;

memo1.Width:=Info.Width - memo1.Left - 30;

end;

procedure TInfo.RadioGroup1Click(Sender: TObject);

begin

case RadioGroup1.ItemIndex of

0: begin

ifFileExists('info_about_autors') then

Memo1.Lines.LoadFromFile('info_about_autors')

elseshowmessage('Yyyyps file is fucking shit!');

end;

1: if FileExists('info_about_program') then

Memo1.Lines.LoadFromFile('info_about_program')

elseshowmessage('Yyyyps file is fucking shit!');

// 2:

// 3:

end;

end;

end.

unitLogo_unit;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, ExtCtrls, StdCtrls, jpeg, Buttons, ComCtrls;

type

TLogo = class(TForm)

Button1: TButton;

Memo1: TMemo;

procedure Button1Click(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Logo: TLogo;

implementation

{$R *.dfm}

procedure TLogo.Button1Click(Sender: TObject);

begin

logo.Close;

end;

end.

unitMain_unit;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, Menus, Grids, ComCtrls, StdCtrls, ExtCtrls, jpeg, XPMan;

type

TMainForm = class(TForm)

MainMenu1: TMainMenu;

N1: TMenuItem;

N2: TMenuItem;

N3: TMenuItem;

N4: TMenuItem;

N5: TMenuItem;

N6: TMenuItem;

GB1: TGroupBox;

UpDown1: TUpDown;

UpDown2: TUpDown;

Button1: TButton;

Edit1: TEdit;

Edit2: TEdit;

Label1: TLabel;

Label2: TLabel;

SG1: TStringGrid;

SG2: TStringGrid;

SG3: TStringGrid;

Button2: TButton;

Button3: TButton;

StaticText1: TStaticText;

StaticText2: TStaticText;

CheckBox1: TCheckBox;

CheckBox2: TCheckBox;

GB2: TGroupBox;

SG4: TStringGrid;

N11: TMenuItem;

N21: TMenuItem;

Button4: TButton;

SG5: TStringGrid;

GB3: TGroupBox;

GB4: TGroupBox;

Button5: TButton;

Button6: TButton;

N7: TMenuItem;

N8: TMenuItem;

N9: TMenuItem;

SaveDialog1: TSaveDialog;

OpenDialog1: TOpenDialog;

StaticText3: TStaticText;

StaticText4: TStaticText;

Edit3: TEdit;

Edit4: TEdit;

XPManifest1: TXPManifest;

Image1: TImage;

StaticText5: TStaticText;

procedure N5Click(Sender: TObject);

procedure Button6Click(Sender: TObject);

procedure N8Click(Sender: TObject);

procedure N3Click(Sender: TObject);

procedure N7Click(Sender: TObject);

procedure N9Click(Sender: TObject);

procedure Button5Click(Sender: TObject);

procedure N21Click(Sender: TObject);

procedure N11Click(Sender: TObject);

procedure N6Click(Sender: TObject);

procedure SG1KeyPress(Sender: TObject; var Key: Char);

procedure Button4Click(Sender: TObject);

procedure SG3KeyPress(Sender: TObject; var Key: Char);

procedure Button3Click(Sender: TObject);

procedure Button2Click(Sender: TObject);

procedure SG2KeyPress(Sender: TObject; var Key: Char);

procedure Button1Click(Sender: TObject);

procedure UpDown2Click(Sender: TObject; Button: TUDBtnType);

procedure UpDown1Click(Sender: TObject; Button: TUDBtnType);

procedureFormShow(Sender: TObject);

private

{ Private declarations }

public

{ Public declarations }

end;

var

MainForm: TMainForm;

procedureSaveGrid(Grid:TStringGrid; constFileName:string); // процедурасохранениявфайл

procedureLoadGrid(varGrid:TStringGrid; constFileName:string); // процедуразагрузкиизфайла

procedureOptGrid(GridPrice:TStringGrid; GridTrans:TStringGrid); // оптимизацияматрицы

implementation

usesLogo_unit, Info_unit;

{$R *.dfm}

procedure TMainForm.Button1Click(Sender: TObject);

var

i:integer;

begin

N9.Enabled:=true; //настройкаинтерфейсов

N1.Enabled:=false; //расположения кнопок, комбобоксов и т.д.

GB2.Top:=8; // ...

GB2.Left:=16;

GB2.Height:=321;

GB1.Visible:=false;

GB1.Enabled:=false;

GB2.Visible:=true;

GB2.Enabled:=true;

for i := 1 to SG1.ColCount - 1 do

SG1.Cells[i,0]:='';

for i := 1 to SG1.RowCount - 1 do

SG1.Cells[0,i]:='';

SG1.Cells[0,0]:='Кол-во';

SG1.Top:=GB2.Top + 5;

SG1.Left:=GB2.Width + GB2.Left +4;

SG1.Visible:=true;

SG1.Enabled:=true;

SG3.ColCount:=SG1.RowCount-1;

SG2.ColCount:=SG1.ColCount-1;

SG4.ColCount:=SG1.ColCount;

SG4.RowCount:=SG1.RowCount;

SG5.ColCount:=SG1.ColCount;

SG5.RowCount:=SG1.RowCount;

for i := 0 to SG2.ColCount - 1 do

SG2.Cells[i,0]:=IntToStr(i+1);

for i := 0 to SG3.ColCount - 1 do

SG3.Cells[i,0]:=IntToStr(i+1);

//SG1.FixedColor:=clAqua;

UpDown1.Position:=1;

UpDown2.Position:=1; // ...

end;

procedure TMainForm.Button2Click(Sender: TObject);

var

i,S2,S3:integer;

f:boolean;

begin

n2.Enabled:=true;

f:=true;

S2:=0;// сумма вектору покупателей

S3:=0;// суммаповекторупоставщиков

for i := 0 to SG2.ColCount - 1 do

if SG2.Cells[i,1] = '' then

SG2.Cells[i,1]:='0';

for i := 0 to SG3.ColCount - 1 do

if SG3.Cells[i,1] = '' then

SG3.Cells[i,1]:='0';

for i := 0 to SG2.ColCount - 1 do // считаемсумму

S2:=S2 + StrToInt(SG2.Cells[i,1]); // по вектору покупателей

for i := 0 to SG3.ColCount - 1 do // считаемсуммуповектору

S3:=S3 + StrToInt(SG3.Cells[i,1]); // поставщиков

if (S3 <> S2) or (S2=0) or (S3=0) then // если они не равны между собой или нулевые, тогда

begin

f:=false; // роняем флаг

Showmessage('Некорректный ввод'); // ругаемся

end;

if f then // если всё правильно ввели заходим в цикл

begin

for i := 0 to SG1.ColCount - 1 do // перебиваемвекторав

SG1.Cells[i+1,0]:=SG2.Cells[i,1]; // матрицу SG1

for i := 0 to SG1.RowCount - 1 do //...

SG1.Cells[0,i+1]:=SG3.Cells[i,1]; //...

SG1.Left:=16; // настраиваем интерфейсы

SG1.Top:=8;

Button4.Visible:=true;

Button4.Enabled:=true;

Button4.Left:=SG1.Left;

Button4.Top:= SG1.Top + SG1.Height + 10;

GB2.Visible:=false;

GB2.Enabled:=false;

Showmessage('Теперьвведитецену');

SG1.Options:=SG1.Options + [goEditing]; // разрешаемредактировать SG1, чтобызабитьцены

end;

end;

procedure TMainForm.Button3Click(Sender: TObject); // процедураочисткивекторовпривводепоставщиковипокупателей

var

i:integer;

begin

if CheckBox1.Checked then

for i := 0 to SG2.ColCount - 1 do

SG2.Cells[i,1]:='';

if CheckBox2.Checked then

for i := 0 to SG2.ColCount - 1 do

SG3.Cells[i,1]:=''

end;

procedure TMainForm.Button4Click(Sender: TObject); // проверяемвселиполязаполнены

var

f:boolean;

i,j:integer;

begin

f:=true;

for i := 1 to SG1.ColCount - 1 do

for j := 1 to SG1.RowCount - 1 do

if SG1.Cells[i,j]='' then

f:=false;

if f then

begin

Button4.Visible:=false;

Button4.Enabled:=false;

N4.Enabled:=true;

end

else

showmessage('Невсеполязаполнены!');

end;

procedure TMainForm.Button5Click(Sender: TObject); // кнопкаоптимизация

var

sum,i,j:integer;

begin

sum:=0; // сновасуммапервозок

OptGrid(MainForm.SG1,MainForm.SG4);

for i := 1 to SG4.ColCount - 1 do //

for j := 1 to SG4.RowCount - 1 do //

if SG4.Cells[i,j] <> '' then //

sum:=sum + StrToInt(SG4.Cells[i,j])*StrToInt(SG1.Cells[i,j]); // <<-считаем

Edit3.Text:=IntToStr(sum); // забиваемеёв Edit3

end;

procedure TMainForm.Button6Click(Sender: TObject); // тожеоптимизациядругометодатутвсётожесамоечтоивыше

var

sum,i,j:integer;

begin

sum:=0;

OptGrid(MainForm.SG1,MainForm.SG5);

for i := 1 to SG5.ColCount - 1 do

for j := 1 to SG5.RowCount - 1 do

if SG5.Cells[i,j] <> '' then

sum:=sum + StrToInt(SG5.Cells[i,j])*StrToInt(SG1.Cells[i,j]);

Edit4.Text:=IntToStr(sum);

end;

procedureTMainForm.FormShow(Sender: TObject);

begin

logo.showmodal;

end;

procedure TMainForm.N11Click(Sender: TObject); // <<- МетодЮВУ

var

a,b:array[1..20] of integer;

i,j,sum:integer;

begin

sum:=0; // это сумма перевозок считается в конце

n11.Enabled:=false;

for i := 1 to SG1.ColCount - 1 do // забиваемзначениеА

a[i]:=StrToInt(SG1.Cells[i,0]); // А - векторпокупателей

for i := 1 to SG1.RowCount - 1 do // ЗабиваемзначениеВ

b[i]:=StrToInt(SG1.Cells[0,i]); // В - векторпоставщиков

// Начало цикла заполнения

for j := SG1.RowCount - 1 downto 1 do // начинаем просматривать матрицу

for i := SG1.ColCount - 1 downto 1 do // споследнейячейки

begin

// дальше 3 случая такие же в методе Лебедева

if (a[i] < b[j]) and (a[i] <> 0) then // A<B

begin

SG4.Cells[i,j]:=IntToStr(a[i]);

b[j]:=b[j]-a[i];

a[i]:=0;

end ;

if (a[i] > b[j]) and (b[j] <> 0) then // A>B

begin

SG4.Cells[i,j]:=IntToStr(b[j]);

a[i]:=a[i] - b[j];

b[j]:=0

end;

if (a[i]=b[j]) and (a[i] <> 0) then // A=B

begin

SG4.Cells[i,j]:=IntToStr(a[i]);

a[i]:=0;

b[j]:=0;

end;

end;

// закончился цикл

for i := 0 to SG1.ColCount - 1 do // опять перебивает поставщиков

SG4.Cells[i,0]:=SG1.Cells[i,0]; // ипокупателей...

for i := 0 to SG1.RowCount - 1 do // ...

SG4.Cells[0,i]:=SG1.Cells[0,i]; // ...

for i := 1 to SG4.ColCount - 1 do // исчитаемсуммупервозок

for j := 1 to SG4.RowCount - 1 do //...

if SG4.Cells[i,j] <> '' then //....

begin

sum:=sum + StrToInt(SG4.Cells[i,j])*StrToInt(SG1.Cells[i,j]); // <<--вотона

statictext5.Caption:=statictext5.Caption + '= +' + SG4.Cells[i,j] + '*' + SG1.Cells[i,j];

Edit3.Text:=IntToStr(sum); // дальше снова настройка интерфейсов

SG4.Height:=SG1.Height; //...

SG4.Width:=SG1.Width; //...

GB3.Left:=SG1.Left; //...

if GB4.Enabled=true then

GB3.Left:=GB3.Left + GB4.Width +40;

GB3.Top:=SG1.Top + SG1.Height + 20;

GB3.Height:=SG4.Height + 140;

GB3.Width:=SG4.Width + 40;

GB3.Visible:=true;

GB3.Enabled:=true;

StaticText3.Left:=SG4.Left;

StaticText3.Top:=SG4.Top + SG4.Height + 10;

Edit3.Left:=StaticText3.Left + StaticText3.Width + 2;

Edit3.Top:=StaticText3.Top;//...

end;

procedure TMainForm.N7Click(Sender: TObject);

begin

N1.Enabled:=false; // настройка интерфейсов опять же

GB1.Visible:=true; // ...

GB1.Enabled:=true;

GB1.Width:=310;

GB1.Height:=105;

GB1.Left:=8;

GB1.Top:=8;

SG1.Top:=GB1.Top + GB1.Height + 10;

SG1.Left:=GB1.Left;

SG1.Visible:=true;

SG1.Enabled:=true;

Edit1.Text:='1';

Edit2.Text:='1';

SG1.Cells[0,1]:='1';

SG1.Cells[1,0]:='1';

SG1.Cells[0,0]:= 'Стр.\Стл.'; //...

end;

procedure TMainForm.N8Click(Sender: TObject);

var

i:integer;

begin

if OpenDialog1.Execute then // операторзапускадиалога OpenDialog1

begin

LoadGrid(MainForm.SG1,OpenDialog1.FileName); // процедуразагрузкифайла

n1.Enabled:=false; // настройкаинтерфейсов

n2.Enabled:=true; //...

SG1.Visible:=true;

SG1.Enabled:=true;

SG1.Top:=8;

SG1.Left:=16;

SG1.Width:=SG1.ColWidths[64] * SG1.ColCount + 10;

if SG1.Width > SG1.ColWidths[64] * 8 then

SG1.Width:=SG1.ColWidths[64] * 8 + 10;

SG1.Height:=SG1.RowHeights[24] * SG1.RowCount + 10;

if SG1.Height > SG1.RowHeights[24] * 8 then

SG1.Height:=SG1.RowHeights[24] * SG1.RowCount + 10;

Button4.Visible:=true;

Button4.Enabled:=true;

Button4.Left:=SG1.Left;

Button4.Top:=SG1.Top + SG1.Height + 20;

SG4.ColCount:=SG1.ColCount;

SG4.RowCount:=SG1.RowCount;

SG5.ColCount:=SG1.ColCount;

SG5.RowCount:=SG1.RowCount;

end;

end;

procedure TMainForm.N21Click(Sender: TObject); // <<-- МетодЛебедева

var

a,b:array[1..20] of integer;

c,d:array[1..20] of real;

e:array[1..20,1..20] of real;

i,j,pos,s,t,sum:integer;

num:real;

f:boolean;

begin

n21.Enabled:=false;

for i := 1 to SG1.ColCount - 1 do //ЗабиваемзначенияА

a[i]:=StrToInt(SG1.Cells[i,0]); // А - векторпокупателей

for i := 1 to SG1.RowCount - 1 do //Забиваемзначения B

b[i]:=StrToInt(SG1.Cells[0,i]); // В - векторпоставщиков

for i := 1 to SG1.ColCount - 1 do //Забиваемзначения C

begin // С - вектор средних значений по столбцам

s:=0;//

t:=0; //

for j := 1 to SG1.RowCount - 1 do //

begin //

s:=s+StrToInt(SG1.Cells[i,j]); //

inc(t);//

end; //

c[i]:=s/t;//

end; //

for j := 1 to SG1.RowCount - 1 do //Забиваемзначения D

begin // D - вектор среднихщначений по строкам

s:=0; //

t:=0; //

for i := 1 to SG1.ColCount - 1 do //

begin //

s:=s + StrToInt(SG1.Cells[i,j]); //

inc(t); //

end; //

d[j]:=s/t; //

end; //

for i := 1 to SG1.ColCount - 1 do //ЗабиваемЕ

for j := 1 to SG1.RowCount - 1 do // E - матрица значений:(C + D - цена перевозки в этой клетке)

e[i,j]:=c[i] + d[j] - StrToInt(SG1.Cells[i,j]); //

//Цикл заполнения начало

for j := 1 to SG1.RowCount - 1 do // идём по строкам

begin

pos:=0; // pos - позиция элемента по столбцу(номер столбца)

f:=false; // если f=true цикл заканчивается

repeat // repeat будет повторятся пока значение B соотвествующее текущему номеру строки не станет равно 0

num:=0; // число с которым будем сравнивать каждый элемент в строке

for i := 1 to SG1.ColCount - 1 do // просматриваем все элементы в текущей строке

if (e[i,j] >num) then // ищем самый большой элемент матрицы Е (поэтому numприсволи значение 0 выше)

begin

num:=e[i,j]; // и если нашли такой то запоминаем его в num

pos:=i; // и номер его столбца в pos

end;

e[pos,j]:=0; // обнуляем его в матрице Е чтобы при повторении цикла не выбрать его же так как он самый большо

// далее сравниваем векторы B(поставщиков) и A(покупателей)

// рассматриваем 3 случая A>B A<B A=B

if (a[pos] < b[j]) and (a[pos] <> 0) then // A<B

begin

SG5.Cells[pos,j]:=IntToStr(a[pos]); // забиваем значение (А т.к. А меньше) в новыйстринггрид SG5

b[j]:=b[j] - a[pos]; // вычитаем из Б А

a[pos]:=0; // обнуляем А, т.к. мы его забили в новый СтринГрид

end;

if (a[pos] > b[j]) and (b[j]<>0) then // A<B

begin // делаем тоже самое что и выше только наоборот

SG5.Cells[pos,j]:=IntToStr(b[j]);

a[pos]:=a[pos] - b[j];

b[j]:=0;

end;

if (a[pos] = b[j]) and (b[j]<>0) then //A=B

begin // тоже самое, только в новый СГ забиваем любое или А или В и оба обнуляем

SG5.Cells[pos,j]:=IntToStr(a[pos]);

a[pos]:=0;

b[j]:=0;

end;

if b[j] = 0 then // важныйif после того как прошли всю строку и значение B стало равно 0,

f:=true; // тогда f присваимваемTrue

until f ; // и выходим из цикла repeat

end;

// Цикл заполнения конец

for i := 0 to SG1.ColCount - 1 do // Перебиваем поставщиков и покупателлей в SG5

SG5.Cells[i,0]:=SG1.Cells[i,0]; // ...

for i := 0 to SG1.RowCount - 1 do // ...

SG5.Cells[0,i]:=SG1.Cells[0,i]; // ...

for i := 1 to SG5.ColCount - 1 do // Атутсчитаемсуммупервозок

for j := 1 to SG5.RowCount - 1 do // ...

if SG5.Cells[i,j] <> '' then //...

sum:=sum + StrToInt(SG5.Cells[i,j])*StrToInt(SG1.Cells[i,j]); // <<- вотона sum

Edit4.Text:=IntToStr(sum); // дальшеидётнастройкаинтерфейсов

SG5.Height:=SG1.Height; // ...

SG5.Width:=SG1.Width; //...

GB4.Left:=SG1.Left; //...

if GB3.Enabled=True then //...

GB4.Left:=GB3.Left + GB3.Width + 40; //...

GB4.Top:=SG1.Top + SG1.Height + 20; //...

GB4.Height:=SG5.Height + 140; //...

GB4.Width:=SG5.Width + 40; //...

GB4.Visible:=true; //...

GB4.Enabled:=true; //...

StaticText4.Left:=SG5.Left; //...

StaticText4.Top:=SG5.Top + SG4.Height + 10; //...

Edit4.Left:=StaticText4.Left + StaticText4.Width + 2; //...

Edit4.Top:=StaticText4.Top; //...

end; // МетодЛебедева

procedure TMainForm.N3Click(Sender: TObject); // сохранениевфайл

begin

if SaveDialog1.Execute then

SaveGrid(MainForm.SG1,SaveDialog1.FileName); // собственносамапроцедура

// передаваемые параметры:

// MainForm.SG1 - это наша матрица

// SaveDialog.Filename - это название которое мы введём в диалоге сохранения

end;

procedure TMainForm.N5Click(Sender: TObject);

begin

info.showmodal;

end;

procedure TMainForm.N6Click(Sender: TObject); // выходизпрограммы

var

bs:integer;

begin

bs:=MessageDlg('Хотитевыйти?', mtConfirmation, mbOkCancel,0);

ifbs = mrOk then // еслинажалиОК

MainForm.Close

end;

procedure TMainForm.N9Click(Sender: TObject); // сбросданных

var

i,j,bs:integer;

begin // тут идёт идалог с ОК и Cancel

bs:=MessageDlg('Все данные будут потеряны, сбросить?', mtConfirmation, mbOkCancel,0);

ifbs = mrOkthen // если нажали ОК идёт настройка интерфейсов кнопок визибловинейблдов и т.д.

begin

GB1.Enabled:=false;

GB1.Visible:=false;

GB2.Enabled:=false;

GB2.Visible:=false;

GB3.Enabled:=false;

GB3.Visible:=false;

GB4.Enabled:=false;

GB4.Visible:=false;

N2.Enabled:=false;

N4.Enabled:=false;

N1.Enabled:=true;

N11.Enabled:=true;

N21.Enabled:=true;

N3.Enabled:=true;

Button4.Enabled:=false;

Button4.Visible:=false;

SG1.Options:=SG1.Options + [goEditing];

SG1.Enabled:=false;

SG1.Visible:=false;

for i := 0 to SG1.ColCount - 1 do

for j := 0 to SG1.RowCount - 1 do

SG1.Cells[i,j]:='';

SG1.RowCount:=2;

SG1.ColCount:=2;

for i := 0 to SG4.ColCount - 1 do

for j := 0 to SG4.RowCount - 1 do

SG4.Cells[i,j]:='';

SG4.RowCount:=2;

SG4.ColCount:=2;

for i := 0 to SG5.ColCount - 1 do

for j := 0 to SG5.RowCount - 1 do

SG5.Cells[i,j]:='';

SG5.RowCount:=2;

SG5.ColCount:=2;

for i := 0 to SG3.ColCount - 1 do

for j := 0 to SG3.RowCount - 1 do

SG3.Cells[i,j]:='';

SG3.RowCount:=2;

SG3.ColCount:=1;

for i := 0 to SG2.ColCount - 1 do

for j := 0 to SG2.RowCount - 1 do

SG2.Cells[i,j]:='';

SG2.RowCount:=2;

SG2.ColCount:=1;

end;

end;

procedure TMainForm.SG1KeyPress(Sender: TObject; var Key: Char); // процедураблокировкинекорректоноговвода

begin // здесь key переменная типа CHAR которая возвращает символ нажатой клавиши

ifnot (keyin ['0'..'9',#8]) then // итак если key возвратила нам значение которого нет в списке( цифры 0-9 и код клавиши BackSpace)

key:=#0 // то keyю мы присваимваем код пустого символа, т.е фактически ничего не происходит

end;

procedure TMainForm.SG2KeyPress(Sender: TObject; var Key: Char); // тожесамое

begin

if not (key in ['0'..'9',#8]) then

key:=#0

end;

procedure TMainForm.SG3KeyPress(Sender: TObject; var Key: Char); // иэто

begin

if not (key in ['0'..'9',#8]) then

key:=#0

end;

procedure TMainForm.UpDown1Click(Sender: TObject; Button: TUDBtnType); // выполняетсякогдакликаемна UpDown1

var

i:integer;

begin // здесь делаем чтобы SG1 красиво разъезжался при увеличении строк

SG1.ColCount:=UpDown1.Position;

Edit1.Text:=IntTostr(UpDown1.Position - 1);

for i := 1 to SG1.ColCount - 1 do

SG1.Cells[i,0]:=IntToStr(i);

if SG1.Width < SG1.ColWidths[64] * 8 then

SG1.Width:=SG1.ColWidths[64] * SG1.ColCount + 10;

if (SG1.Width > SG1.ColWidths[64] * 8) and (SG1.ColCount < 8) then

SG1.Width:=SG1.ColWidths[64] * SG1.ColCount + 10;

end;

procedure TMainForm.UpDown2Click(Sender: TObject; Button: TUDBtnType); // тожесамоетолько UpDown2 настолбцы

var

i:integer;

begin

SG1.RowCount:=UpDown2.Position;

Edit2.Text:=IntTostr(UpDown2.Position - 1);

for i := 1 to SG1.RowCount - 1 do

SG1.Cells[0,i]:=IntToStr(i);

if (SG1.Height < SG1.RowHeights[24] * 8) then

SG1.Height:=SG1.RowHeights[24] * SG1.RowCount + 10;

if (SG1.Height > SG1.RowHeights[24] * 8) and (SG1.RowCount < 8) then

SG1.Height:=SG1.RowHeights[24] * SG1.RowCount + 10;

end;

procedureSaveGrid(Grid:TStringGrid; constFileName:string); // процедурасохранениявфайл

var // переменные уже описывал выше

f: textfile; // текстовый файл

i, j: integer;

begin

assignfile(f,Filename); // устанвливаемсоотвествие между физическим и лог файлами

rewrite(f); // открываем файл для записи

writeln(f, grid.colcount); //записываем кол-во столбцов

writeln(f, grid.rowcount); // строк

for i := 0 to grid.colcount - 1 do // ипоочередикаждую

for j := 0 to grid.rowcount - 1 do // ячейку SG1 вотдельнуюстроку

writeln(F, grid.cells[i, j]); // ...

closefile(f); // закрываемфайл

end;

procedureLoadGrid(varGrid:TStringGrid; constFileName:string); // процедуразагрузкиизфайла

var

f: textfile; // всё тот же текстовый файл

temp, i, j: integer; // temp - переменная куда будем считывать значения кол-ва столбцов и строк из файла

tempstr: string; // tempstr - то же что и temp только для значений каждой ячейки

begin

assignfile(f, Filename); // устанвливаемсвязь

reset(f); // открываем для чтения

readln(f, temp); // считываем первую запись

grid.colcount := temp; // она является кол-м столбцов

readln(f, temp); // - вторую

grid.rowcount := temp; // - кол-во строк

for i := 0 to grid.colcount - 1 do // следующиезаписи

for j := 0 to grid.rowcount - 1 do // этозначенияячеек SG

begin //

readln(F, tempstr); //тут мы их читаем

grid.cells[i, j] := tempstr; //тут записываем в SG

end;

closefile(f); // закрываем файл

end;

procedureOptGrid(GridPrice:TStringGrid;GridTrans:TStringGrid); // самое интересное - процедура оптимизации )

var

i,j,k,l,m,n,func:integer;

a,b:array[1..20,1..20] of integer;

flag,flag0:boolean;

begin // поехали

for i := 1 toGridPrice.ColCount - 1 do // Перебиваем значение матрицы цен

for j := 1 to GridPrice.RowCount - 1 do // вматрицуА

a[i,j]:=StrToInt(GridPrice.Cells[i,j]); //

for i := 1 toGridTrans.ColCount - 1 do // Перебиваем значение матрицы перевозок

for j := 1 to GridTrans.RowCount - 1 do // вматрицу B

ifGridTrans.Cells[i,j]='' then // если встретили пустую ячейку

b[i,j]:=0 // то вВ забиваем 0

else // иначе

b[i,j]:=StrToInt(GridTrans.Cells[i,j]);// забиваем значение ячейки

m:=GridTrans.RowCount-1; // чтобы удобнее было работать дальше

n:=GridTrans.ColCount-1; //

repeat

flag0:=true; // глобальный флаг, он контролирует повторение цикла Repeat

for i := 1 to n - 1 do // эти 4 for'аразбивают

for j := 1 to m - 1 do // матрицу на отдельны квадраты

for k := i+1 to n do // ...

for l := j+1 to m do // ...

if flag0 then // это условие для того чтобы цикл

// после того как нашёл квдрат в ктором поменял

// значения не поторялся заново

begin

begin

flag:=true; // этот флаг, он отвечает за такое дело:

// если мы нашли квадрат в котором

// выполняется какое-то условие

// которое задано ниже, то мы

// делаем его false и следующие условия

// уже не буду выполнятся

func:=a[i,j]-a[k,j]+a[k,l]-a[i,l]; // это функция - если она больше 0

// то работаем с главной диагональю

// если нет то с побочной

if (func> 0) and flag then //главнаядиагональ

begin

if (b[i,j]=0) or (b[k,l]=0) then // если хотя бы один нулевой

flag:=false; // роняемфлаг

if (b[i,j]=b[k,l]) and flag then // элементыравны

begin // выполняем обмен

b[k,j]:=b[k,j] + b[i,j];

b[i,l]:=b[i,l] + b[i,j];

b[i,j]:=0;

b[k,l]:=0;

flag:=false;

flag0:=false; // роняем флаг - произошёл обмен

end;

if (b[i,j] > b[k,l]) andflagthen // первый больше второго

begin // обмен

b[k,j]:=b[k,j] + b[k,l];

b[i,l]:=b[i,l] + b[k,l];

b[i,j]:=b[i,j] - b[k,l];

b[k,l]:=0;

flag:=false;

flag0:=false; // роняем флаг произошёл обмен

end;

if (b[i,j] < b[k,l]) and flag then // первыйменьшевторого

begin // обмен

b[k,j]:=b[k,j] + b[i,j];

b[i,l]:=b[i,l] + b[i,j];

b[k,l]:=b[k,l] - b[i,j];

b[i,j]:=0;

flag:=false;

flag0:=false; // роняемфлагпроизошёлобмен

end;

end; // закончили с главной диагональю

if (func< 0) andflagthen // поехали тоже самое с побочной

begin

if (b[k,j]=0) or (b[i,l]=0) then // еслинулевые

flag:=false; // тогда делаем flagfalse

if (b[k,j]=b[i,l]) and flag then // элементыравны

begin // обмен

b[i,j]:=b[i,j] + b[k,j];

b[k,l]:=b[k,l] + b[k,j];

b[k,j]:=0;

b[i,l]:=0;

flag:=false;

flag0:=false; // роняем флаг произошёл обмен

end;

if (b[k,j] > b[i,l]) and flag then // третийбольшечетвёртого

begin // обмен

b[i,j]:=b[i,j] + b[i,l];

b[k,l]:=b[k,l] + b[i,l];

b[k,j]:=b[k,j] - b[i,l];

b[i,l]:=0;

flag:=false;

Flag0:=false; // роняем флаг произошёл обмен

end;

if (b[k,j] < b[i,l]) and flag then // третийменьшечетвёртого

begin // обмен

b[i,j]:=b[i,j] + b[k,j];

b[k,l]:=b[k,l] + b[k,j];

b[i,l]:=b[i,l] - b[k,j];

b[k,j]:=0;

flag:=false;

Flag0:=false; // роняемфлагпроизошёлобмен

end;

end; // закончили с побочной диагональю

end;

end;

until flag0 ; // тут вот смысл репит-антила поясню:

// будем его делать пока цикл не пройдёт так,

// что flag0 не упадёт ни разу,

// что значит что всё оптимизировалось

for i := 1 toGridTrans.ColCount - 1 do // перебиваем значения из Вв матрицу перевозок

for j := 1 to GridTrans.RowCount - 1 do // ...

if b[i,j] <> 0 then //

GridTrans.Cells[i,j]:=IntToStr(b[i,j])//

else //

GridTrans.Cells[i,j]:='';//

showmessage('Матрица оптимизированна!'); // ...

end;

end.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]