简体   繁体   中英

Counting unique values of record in Pascal

I struggle to find how to check how many unique values are in one of elements in array of records.

This is what I mean: I have a record containing 1,1,1,2,2,3,5,8 In python I would use set() to find out that there are 5 unique values (1,2,3,5,8). How to do it in Pascal?

Thank you in advance!

There is no built-in way to do that in Pascal. From your question, I assume that your records have just one number. I see two ways to do it. First, if the numbers are from a limited range, say 1 to 1,000,000, set up a boolean array, say:

var InList : array[ 1 .. 1000000] of boolean;

Initialize it to false:

fillchar( InList, sizeof( InList), 0);

Then go through all of your records and set the corresponding element to true. For instance, if the first record value is 123, then:

InList[ 123] := true; (but refer to your record to get the 123).

Then after you have gone through all of your records, go through InList and count the number of trues:

count := 0;

for i := 1 to 1000000 do 
if InList[ i] then inc( count);

The second way, which doesn't depend on the values being from a limited set, is to first sort your array of records (use a good sorting algorithm if you have a large number of records). Then go through the list and count the number this way:

Assume you have RecordList with NumberOfRecords records in it.

sort RecordList

count := 1; // count the first one!

for i := 2 to NumberOfRecords do
if RecordList[ i] <> RecordList[ i - 1] then inc( count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM