Vanilla_Fury

laba_5_1_del_v3

Apr 11th, 2021
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 15.46 KB | None | 0 0
  1. unit laba_5_1_f1;
  2.  
  3. interface
  4.  
  5. uses
  6.   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  7.   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.StdCtrls, System.RegularExpressions,
  8.   Vcl.ExtCtrls, Vcl.ComCtrls, System.UITypes, MyList;
  9.  
  10. type
  11.     TArrStr = Array of String;
  12.  
  13.  
  14.     TFormMain = class(TForm)
  15.     MainMenu1: TMainMenu;
  16.     NHelp: TMenuItem;
  17.     NAuthor: TMenuItem;
  18.     OpenDialog1: TOpenDialog;
  19.     NFile: TMenuItem;
  20.     NOpen: TMenuItem;
  21.     NSaveAs: TMenuItem;
  22.     SaveDialog1: TSaveDialog;
  23.     NSave: TMenuItem;
  24.     NTask: TMenuItem;
  25.     LabelToMeasureScreenOfUser: TLabel;
  26.     MemoInputList: TMemo;
  27.     MemoOutput: TMemo;
  28.     ButtonAccept: TButton;
  29.     MemoInputArray: TMemo;
  30.     LabelList: TLabel;
  31.     LabelArray: TLabel;
  32.     LabelAnswer: TLabel;
  33.     BalloonHint1: TBalloonHint;
  34.     procedure NAuthorClick(Sender: TObject);
  35.     procedure NOpenClick(Sender: TObject);
  36.     procedure NSaveAsClick(Sender: TObject);
  37.     procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  38.     procedure FormCreate(Sender: TObject);
  39.     procedure NSaveClick(Sender: TObject);
  40.     procedure NTaskClick(Sender: TObject);
  41.     function MultPixels(PixQuant: Integer) : Integer;
  42.     procedure MemoInputListChange(Sender: TObject);
  43.     procedure ButtonAcceptClick(Sender: TObject);
  44.  
  45.     procedure ComputeAndOutputAnswer(List: TMyList; Arr: TArrInt);
  46.  
  47.     private
  48.         MultPix: Single;
  49.         StrFile: String;
  50.         IsSaved: Boolean;
  51.     public
  52.  
  53.     end;
  54.  
  55. const
  56.     RegExForNumber = '[1-9]\d{0,2}';
  57.     CaptionHereWillBeAnswer = 'Здесь будет ответ';
  58.  
  59. var
  60.     FormMain: TFormMain;
  61.  
  62. implementation
  63. {$R *.dfm}
  64.  
  65. function FindRegEx(SInput, StrRegEx: String; StrIfNothingFound: String = '') : TArrStr; forward;
  66.  
  67. //******************************************************************************
  68. // Ввод данных
  69.  
  70. procedure TFormMain.MemoInputListChange(Sender: TObject);
  71. var
  72.     Strs: TArrStr;
  73.     StrOneNumber, TextTemp: String;
  74.     i, SelStartTemp: Integer;
  75.     HasSpaceAtTheEnd: Boolean;
  76.     Point: TPoint;
  77.  
  78. begin
  79.     TextTemp := '';
  80.     with Sender as TMemo do
  81.     begin
  82.         HasSpaceAtTheEnd := (Length(Text) > 0) and
  83.             ((Text[High(Text)] = ' ') or (Text[High(Text)] = #10));
  84.         SelStartTemp := SelStart;
  85.         Strs := FindRegEx(Text, '\d+');
  86.  
  87.         if Length(Strs) > 999 then
  88.         begin
  89.             SetLength(Strs, 999);
  90.             BalloonHint1.Title := 'Предупреждение';
  91.             BalloonHint1.Description := 'Максисальное количество чисел - 999';
  92.             Point.X := Round(Width * 2 / 3);
  93.             Point.Y := Height;
  94.             Balloonhint1.ShowHint(ClientToScreen(Point));
  95.         end;
  96.  
  97.         for i := 0 to High(Strs) do
  98.         begin
  99.             StrOneNumber := FindRegEx(Strs[i], RegExForNumber)[0];
  100.             TextTemp := TextTemp + StrOneNumber;
  101.             if i <> High(Strs) then
  102.                 TextTemp := TextTemp + ' ';
  103.         end;
  104.  
  105.         if HasSpaceAtTheEnd then
  106.                 TextTemp := TextTemp + ' ';
  107.  
  108.         if Text <> TextTemp then
  109.         begin
  110.             if Text <> TextTemp + ' ' then
  111.             begin
  112.                 BalloonHint1.Title := 'Предупреждение';
  113.                 BalloonHint1.Description := 'Разрешены только целые числа от 1 до 999.';
  114.                 Point.X := Round(Width * 2 / 3);
  115.                 Point.Y := Height;
  116.                 Balloonhint1.ShowHint(ClientToScreen(Point));
  117.             end;
  118.  
  119.             Text := TextTemp;
  120.             SelStart := SelStartTemp;
  121.         end;
  122.     end;
  123.  
  124.     if (MemoInputList.Text <> '') and (MemoInputArray.Text <> '') then
  125.         ButtonAccept.Enabled := True
  126.     else
  127.         ButtonAccept.Enabled := False;
  128.  
  129.     NSaveAs.Enabled := False;
  130.     NSave.Enabled := False;
  131.  
  132.     MemoOutput.Text := CaptionHereWillBeAnswer;
  133. end;
  134.  
  135. procedure TFormMain.ButtonAcceptClick(Sender: TObject);
  136. var
  137.     StrsMemoList, StrsMemoArray: TArrStr;
  138.     Str: String;
  139.     MyList, MyList2: TMyList;
  140.     Arr: TArrInt;
  141.     i, Number: Integer;
  142.     IsCorrect: Boolean;
  143.     Current: PNode;
  144.  
  145. begin
  146.     IsCorrect := True;
  147.  
  148.     StrsMemoList := FindRegEx(MemoInputList.Text, RegExForNumber);
  149.     StrsMemoArray := FindRegEx(MemoInputArray.Text, RegExForNumber);
  150.  
  151.     MyList.HeadNode := nil;
  152.     for Str in StrsMemoList do
  153.         AddNodeInList(MyList, StrToInt(Str));
  154.  
  155.     MyList2.HeadNode := nil;
  156.     for Str in StrsMemoArray do
  157.         AddNodeInList(MyList2, StrToInt(Str));
  158.  
  159.     Arr := ConvertListIntoArray(MyList2);
  160.  
  161.     MemoInputArray.Clear();
  162.     for Number in Arr do
  163.         With MemoInputArray do
  164.             Text := Text + IntToStr(Number) + ' ';
  165.     MemoInputList.Clear();
  166.     Current := MyList.HeadNode;
  167.     while Current <> nil do
  168.     begin
  169.         With MemoInputList do
  170.             Text := Text + IntToStr(Current.Number) + ' ';
  171.         Current := Current.NextNode;
  172.     end;
  173.  
  174.     if Length(Arr) <> MyList.ListSize then
  175.     begin
  176.         ShowMessage('Числа в массиве не соответствуют реальному размеру списка');
  177.         IsCorrect := False;
  178.     end;
  179.  
  180.     i := 0;
  181.     while IsCorrect and (i < Length(Arr)) do
  182.     begin
  183.         if Arr[i] > MyList.ListSize then
  184.         begin
  185.             ShowMessage('Числа в массиве не соответствуют реальному размеру списка');
  186.             IsCorrect := False;
  187.         end
  188.         else
  189.             Inc(i);
  190.     end;
  191.  
  192.     if IsCorrect then
  193.     begin
  194.         ComputeAndOutputAnswer(MyList, Arr);
  195.         NSaveAs.Enabled := True;
  196.         NSave.Enabled := StrFile <> '';
  197.     end;
  198. end;
  199.  
  200. procedure TFormMain.ComputeAndOutputAnswer(List: TMyList; Arr: TArrInt);
  201. var
  202.     Current, ToSwapWith: PNode;
  203.     SerNum, i, j: Integer;
  204.     ListOut: TMyList;
  205.  
  206. begin
  207.     MemoOutput.Clear();
  208.     ListOut.HeadNode := nil;
  209.  
  210.     for SerNum in Arr do
  211.     begin
  212.         Current := List.HeadNode;
  213.         i := 1;
  214.         while i < SerNum do
  215.         begin
  216.             Current := Current.NextNode;
  217.             Inc(i);
  218.         end;
  219.  
  220.         AddNodeInList(ListOut, Current.Number);
  221.     end;
  222.  
  223.     Current := ListOut.HeadNode;
  224.     while Current <> nil do
  225.     begin
  226.         With MemoOutput do
  227.             Text := Text + IntToStr(Current.Number) + ' ';
  228.         Current := Current.NextNode;
  229.     end;
  230. end;
  231.  
  232.  
  233. //******************************************************************************
  234. // Работа с файлами
  235.  
  236. procedure TFormMain.NOpenClick(Sender: TObject);
  237. const
  238.     ErrorDuringInputOccured = 'Возникла ошибка при открытии файла.' + #10#13 +
  239.                 'Пожалуйста, выберите файл нужного формата(.datgrad) с ' +
  240.                 'корректными данными.';
  241.  
  242. var
  243.     FileInput : TextFile;
  244.     PathToFile, String1: String;
  245.  
  246. begin
  247.     if not IsSaved and (MessageDlg('Вы хотите сохранить текущие данные?' +
  248.         #10#13 + 'Иначе после открытия файла текущие записи будут удалены.',
  249.         mtConfirmation, [mbYes, mbNo], 0) = mrYes) then
  250.         NSaveClick(Self);
  251.  
  252.     if (IsSaved or (MessageDlg('Вы уверены, что хотите открыть другой файл?' + #10#13 +
  253.         'Все текущие записи будут удалены.', mtConfirmation, [mbYes, mbCancel], 0) = mrYes))
  254.         and OpenDialog1.Execute then
  255.     begin
  256.         PathToFile := OpenDialog1.FileName;
  257.         try
  258.             AssignFile(FileInput, PathToFile);
  259.             Reset(FileInput);
  260.  
  261.             Readln(FileInput, String1);
  262.             MemoInputList.Text := String1;
  263.             Readln(FileInput, String1);
  264.             MemoInputArray.Text := String1;
  265.  
  266.             CloseFile(FileInput);
  267.             ButtonAcceptClick(Self);
  268.         except
  269.             ShowMessage(ErrorDuringInputOccured);
  270.         end;
  271.     end;
  272. end;
  273.  
  274. procedure TFormMain.NSaveAsClick(Sender: TObject);
  275. var
  276.     FileOutput : TextFile;
  277.     StrFilePath: String;
  278.     ShouldNotRepeat: Boolean;
  279.     Point: TPoint;
  280.  
  281. begin
  282.     try
  283.         repeat
  284.             ShouldNotRepeat := True;
  285.             if SaveDialog1.Execute then
  286.             begin
  287.                 StrFilePath := SaveDialog1.FileName;
  288.                 StrFilePath := FindRegEx(StrFilePath, '.+\.txt', StrFilePath + '.txt')[0];
  289.  
  290.                 if FileExists(StrFilePath) then
  291.                     if MessageDlg('Такой файл уже существует.' +
  292.                         #10#13 + 'Вы хотите перезаписать файл? Это действие невозможно отменить.',
  293.                         mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  294.                         ShouldNotRepeat := True
  295.                     else
  296.                         ShouldNotRepeat := False
  297.                 else
  298.                     ShouldNotRepeat := True;
  299.  
  300.                 if ShouldNotRepeat then
  301.                 begin
  302.                     AssignFile(FileOutput, StrFilePath);
  303.                     Rewrite(FileOutput);
  304.  
  305.                     Write(FileOutput, 'Введённый список:' + #10#13
  306.                         + MemoInputList.Text + #10#13 + 'Введённый массив:'
  307.                         + #10#13 + MemoInputArray.Text + #10#13 + 'Ответ:'
  308.                         + #10#13 + MemoOutput.Text + #10#13);
  309.  
  310.                     CloseFile(FileOutput);
  311.                     IsSaved := True;
  312.                     BalloonHint1.Title := 'Готово';
  313.                     BalloonHint1.Description := 'Ответ успешно записан в файл.';
  314.                     Point.X := Round(MemoOutput.Left + MemoOutput.Width * 2 / 3);
  315.                     Point.Y := MemoOutput.Top + MemoOutput.Height;
  316.                     Balloonhint1.ShowHint(ClientToScreen(Point));
  317.  
  318.  
  319.                     NSave.Enabled := True;
  320.                     StrFile := StrFilePath;
  321.                 end;
  322.             end;
  323.         until ShouldNotRepeat;
  324.     except
  325.        ShowMessage('Не удается открыть файл для вывода данных или записать в него данные.');
  326.     end;
  327. end;
  328.  
  329. procedure TFormMain.NSaveClick(Sender: TObject);
  330. var
  331.     FileOutput : TextFile;
  332.  
  333. begin
  334.     if MessageDlg('Вы хотите перезаписать файл "' + StrFile + '"?' + #10#13 +
  335.         'Это действие невозможно отменить.', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
  336.         if FileExists(StrFile) then
  337.         begin
  338.             AssignFile(FileOutput, StrFile);
  339.             Rewrite(FileOutput);
  340.  
  341.             Write(FileOutput, 'Введённый список:' + #10#13
  342.                 + MemoInputList.Text + #10#13 + 'Введённый массив:' + #10#13
  343.                 + MemoInputArray.Text + #10#13 + 'Ответ:'
  344.                 + #10#13 + MemoOutput.Text + #10#13);
  345.  
  346.             CloseFile(FileOutput);
  347.             IsSaved := True;
  348.         end
  349.         else
  350.         begin
  351.             ShowMessage('Этого файла уже не существует.');
  352.             StrFile := '';
  353.             NSave.Enabled := False;
  354.             NSaveAsClick(Self);
  355.         end;
  356. end;
  357.  
  358.  
  359. //******************************************************************************
  360. // Form Create
  361.  
  362. procedure TFormMain.FormCreate(Sender: TObject);
  363. begin
  364.     MultPix := LabelToMeasureScreenOfUser.Width / 100;
  365.     StrFile := '';
  366.     IsSaved := True;
  367.     MemoOutput.Text := CaptionHereWillBeAnswer;
  368. end;
  369.  
  370. //******************************************************************************
  371. // Прочее
  372.  
  373. procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
  374. begin
  375.     CanClose := IsSaved or (MessageDlg('Вы уверены, что хотите выйти из программы?' +
  376.         #10#13 + 'Все несохранённые данные будут утеряны.',
  377.         mtConfirmation, [mbYes, mbNo], 0) = mrYes);
  378. end;
  379.  
  380. procedure TFormMain.NAuthorClick(Sender: TObject);
  381. begin
  382.     ShowMessage('Панев Александр, гр. 051007' + #10#13 + 'Минск, 2021');
  383. end;
  384.  
  385. procedure TFormMain.NTaskClick(Sender: TObject);
  386. begin
  387.     ShowMessage('Дан неупорядоченный линейный односвязный список и массив, ' +
  388.     'содержащий номера соответствующих элементов в упорядоченном списке. ' +
  389.     'Перестроить данный список в соответствии с номерами, заданными массивом.');
  390. end;
  391.  
  392. function FindRegEx(SInput, StrRegEx: String; StrIfNothingFound: String = '') : TArrStr;
  393. var
  394.     ArrStr: TArrStr;
  395.     RegEx: TRegEx;
  396.     MatchCollection: TMatchCollection;
  397.     i: Integer;
  398. begin
  399.     RegEx := TRegEx.Create(StrRegEx);
  400.     MatchCollection := RegEx.Matches(SInput);
  401.     SetLength(ArrStr, MatchCollection.Count);
  402.     for i := 0 to MatchCollection.Count - 1 do
  403.         ArrStr[i] := MatchCollection.Item[i].Value;
  404.  
  405.     if (Length(ArrStr) < 1) then
  406.         ArrStr := [StrIfNothingFound];
  407.     Result := ArrStr;
  408. end;
  409.  
  410. function TFormMain.MultPixels(PixQuant: Integer) : Integer;
  411. begin
  412.     Result := Round(PixQuant * MultPix);
  413. end;
  414.  
  415. end.
  416.  
  417.  
  418.  
  419.  
  420.  
  421.  
  422.  
  423.  
  424.  
  425.  
  426. unit MyList;
  427.  
  428. interface
  429.  
  430. uses System.SysUtils;
  431.  
  432. type
  433.     TArrInt = Array of Integer;
  434.  
  435.     PNode = ^TNode;
  436.     TNode = Record
  437.         Number: Integer;
  438.         NextNode: PNode;
  439.     End;
  440.     TMyList = Record
  441.         HeadNode: PNode;
  442.         ListSize: Integer;
  443.     End;
  444.  
  445.     procedure AddNodeInList(var List: TMyList; Number: Integer);
  446.     function ConvertListIntoArray(var List: TMyList) : TArrInt;
  447.  
  448. implementation
  449.  
  450. procedure AddNodeInList(var List: TMyList; Number: Integer);
  451. var
  452.     NewNode, CurrentNode: PNode;
  453.     ProcessIsNotDone: Boolean;
  454.  
  455. begin
  456.     New(NewNode);
  457.     with List do
  458.     begin
  459.         if HeadNode = nil then
  460.         begin
  461.             HeadNode := NewNode;
  462.             ListSize := 1;
  463.         end
  464.         else
  465.         begin
  466.             ProcessIsNotDone := True;
  467.             CurrentNode := HeadNode;
  468.             while (CurrentNode <> nil) and ProcessIsNotDone do
  469.             begin
  470.                 if CurrentNode.Number = Number then
  471.                     ProcessIsNotDone := False
  472.                 else
  473.                     if CurrentNode.NextNode = nil then
  474.                     begin
  475.                         CurrentNode.NextNode := NewNode;
  476.                         Inc(ListSize);
  477.                         ProcessIsNotDone := False;
  478.                     end
  479.                     else
  480.                         CurrentNode := CurrentNode.NextNode;
  481.             end;
  482.         end;
  483.  
  484.         NewNode.Number := Number;
  485.         NewNode.NextNode := nil;
  486.     end;
  487. end;
  488.  
  489. function ConvertListIntoArray(var List: TMyList) : TArrInt;
  490. var
  491.     QuantityOfElem: Integer;
  492.     CurrentNode: PNode;
  493.     ArrOutput: TArrInt;
  494.  
  495. begin
  496.     SetLength(ArrOutput, 8);
  497.     QuantityOfElem := 0;
  498.  
  499.     CurrentNode := List.HeadNode;
  500.     while CurrentNode <> nil do
  501.     begin
  502.         Inc(QuantityOfElem);
  503.         if QuantityOfElem > Length(ArrOutput) then
  504.             SetLength(ArrOutput, Round(Length(ArrOutput) * 1.5));
  505.  
  506.         ArrOutput[QuantityOfElem - 1] := CurrentNode.Number;
  507.         CurrentNode := CurrentNode.NextNode;
  508.     end;
  509.     SetLength(ArrOutput, QuantityOfElem);
  510.     Result := ArrOutput;
  511. end;
  512.  
  513. end.
Advertisement
Add Comment
Please, Sign In to add comment