The code below groups a list by either number or letter, as seen below:
1A, 1B, 2A, 2B, 3A, 3B, 4A, 4B, 5A, 5B
or
1A, 2A, 3A, 4A, 5A, 1B, 2B, 3B, 4B, 5B
The option is configurable by the user via the loopOrder variable. The code essentially sets the first loop (i loop) or third loop (k loop) to 1 to negate it and then sets the other loop to 2.
Code below:
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm2 = class(TForm)
ListBox1: TListBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.FormCreate(Sender: TObject);
var
loopOrder, i, j, k, x, y: integer;
outputList: array [1 .. 5, 1 .. 2] of string;
begin
loopOrder := 2; //1 for 1A, 2A, 3A etc. 2 for 1A, 1B, 2A etc.
for i := 1 to loopOrder do
begin
for j := 1 to 5 do
begin
x := 2;
if loopOrder = 2 then
x := 1;
for k := 1 to x do
begin
if loopOrder = 1 then
y := k
else
y := i;
if y = 1 then
outputList[j, y] := inttostr(j) + 'A'
else
outputList[j, y] := inttostr(j) + 'B';
ListBox1.Items.Add(outputList[j, y]);
end;
end;
end;
end;
end.
Is there a cleaner way of doing this that perhaps uses less variables?