[Pascal] Suggestion for new auto-genrated code

The current auto-generated code takes a lot of characters and feels a little bit counterintuitive in my opinion.

String.Split is very powerful and needs way less code. And with ReadLn there is no need for type conversion.

Examples:

program Example_1;
{$H+}
uses
  SysUtils, Classes;

var
  Input: String;
  SplittedInput: Array of String;
  Index: Int32;
begin
  ReadLn(Input); // 123 321 456 654
  SplittedInput := Input.Split(' ');
  
  for Index := 0 to High(SplittedInput) do
  begin
    WriteLn(SplittedInput[Index]);
  end;
end.

Output:
123
321
456
654


program Example_2;
{$H+}

uses
  SysUtils, Classes;

var
  Input: String;
  SplittedInput: Array of String;
  NumbersOfLines, Index: Int32;
begin
  ReadLn(NumbersOfLines);

  repeat
    ReadLn(Input);   // One; Two; Three; Test;
    SplittedInput := Input.Split('; ', TStringSplitOptions.ExcludeEmpty);
    
    for Index := 0 to High(SplittedInput) do
    begin
      WriteLn(SplittedInput[Index]);
    end;

    Dec(NumbersOfLines);
  until NumbersOfLines = 0;
end.

Output:
One
Two
Three
Test


Links:

System.SysUtils.TStringHelper.Split

TStringSplitOptions

2 Likes

Agreed. This is much more elegant. I would add that we don’t need the Classes unit either.

Also in Pascal, the line “flush(StdErr); flush(output); // DO NOT REMOVE” by default at the end of the script is not necessary (output is flushed when program terminates). It may be useful though in game loops (to make sure entry is flushed before next loop).

Also in Pascal, it is possible to read integers/reals directly from input. Here would be a simplified version of the generated code for the Temperatures puzzle:

var
    n, i: integer;
    temps: array of integer;
begin
    readln(N); // read one line containing an integer

    // read an array of integers of size N
    setlength(temps, N);
    for i := 0 to N-1 do
        read(temps[i]);
    readln;