• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 541
  • Last Modified:

Sorting numbers

I have a listbox containing rows of numbers: 7 numbers per row separated by commas, such as:

27,11,44,23,3,9,7
15,6,27,22,44,2,4
15,35,11,27,42,4,6
etc

When I click a button, I need each of these numbers to be added to another listbox, one per line, in acending order (sorted):

2
4
4
6
7
9
11
11
etc

I am using Delphi 6.  Many thanks for your help.
0
rincewind666
Asked:
rincewind666
1 Solution
 
Ferruccio AccalaiSenior developer, analyst and customer assistance Commented:
function CompareInt(List: TStringList; Index1, Index2: Integer): Integer;
var
  d1, d2: Integer;
  r1, r2: Boolean;
  function IsInt(AString: string; var AInteger: Integer): Boolean;
  var
    Code: Integer;
  begin
    Val(AString, AInteger, Code);
    Result := (Code = 0);
  end;

begin
  r1 := IsInt(List[Index1], d1);
  r2 := IsInt(List[Index2], d2);
  Result := ord(r1 or r2);
  if Result <> 0 then
  begin
    if d1 < d2 then
      Result := -1
    else if d1 > d2 then
      Result := 1
    else
      Result := 0;
  end
  else
    Result := lstrcmp(PChar(List[Index1]), PChar(List[Index2]));
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  l: TStringList;
  i: Integer;
begin
  l := TStringList.Create;
  try
    ListBox2.Items.BeginUpdate;
    ListBox2.Clear;
    for i := 0 to ListBox1.Items.Count-1 do
    begin
      l.Delimiter := ',';
      l.DelimitedText := ListBox1.Items[i];
      ListBox2.Items.AddStrings(l);
    end;
  finally
    l.Assign(ListBox2.Items);
    l.CustomSort(CompareInt);
    ListBox2.Items.Assign(l);
    ListBox2.Items.EndUpdate;
    l.free;
  end;
end;

Open in new window

0
 
ITugayCommented:
Looks like homework.
0
 
rincewind666Author Commented:
Many thanks Ferruccio68. Your help is greatly appreciated.
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now