[fpc-pascal] sorting and merging array of records

Sven Barth pascaldragon at googlemail.com
Tue Jan 10 11:39:44 CET 2012


Am 10.01.2012 05:14, schrieb waldo kitty:
> my problem is that i cannot find any similar examples where an array of
> records is built, sorted and duplicates are eliminated based on specific
> factors of the two records being compared...
>
> uncle has been failing me for the last several hours and i'm loosing
> sight of what i'm trying to get done... i've seen references to using a
> tstringlinst as well as something apparently non-existent called a
> tarray... in all of the stuff i've seen on tstringlinst, there's nothing
> that i find that is close to what i'm (thinking i'm) looking for... and
> here's where i keep getting diverted away from the final goal due to
> trying to follow everything else :/

My suggestion is to use a generic list from unit fgl.

Following example:

type
   TSatDataList = specialize TFPGList<three_line_data>;

In the following I assume that you know how to use classes, if not feel 
free to ask back ;)

When now reading the file you do the following (based on your code):

Procedure Input_Satellite(aInputFile: TextFile; aList: TSatDataList);
   var
     data: three_line_data;
   begin
   if not EOF(aInputFile) then
     begin
     Readln(aInputFile,data.satname);
     Readln(aInputFile,data.satdata[1]);
     Readln(aInputFile,data.satdata[2]);
     aList.Add(data);
     end; {if}
   end; {Procedure Input_Satellite}

For checking whether a element in the list is the same as another one 
you can do the following (assuming the new item is called "data"):

duplicate := False;
for i := 0 to aList.Count - 1 do
   if IsSame(aList[i], data) then begin // I don't know how exactly your 
check looks like, so I just put a placeholder here :)
     // correct the old data instead of inserting
     aList[i].{...}
     duplicate := True;
     Break; // if you're sure that there is no more dupliacate in the 
list you can break here
   end;

if not dupliate then
   aList.Add(data); // no duplicate found so add the new element

For sorting the list you need to define a compare function:

function SatDataCompare(aLeft, aRight: three_line_data): Integer;
// aLeft and aRight are of the same type with which you specialized the 
TFPGList
// returns
// -1 if aLeft < aRight
// 0 if aLeft = aRight
// 1 if aLeft > aRight
begin
   // compare the two items and return the correct value
end;

// somewhere else:
aList.Sort(@SatDataCompare);

What I wrote here might not be perfect, but it should give you a start.

Regards,
Sven



More information about the fpc-pascal mailing list