Finding common elements in two arrays

前端 未结 2 1919
北恋
北恋 2021-01-07 05:04

I’ve declared a type similar to the following.

type
  TLikes = record
    Name            : string[20];
    favColours  : array of string[20];

  faves     =         


        
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 05:31

    You're dealing with a many-to-many relationship here.
    If it were a database that means you'd put in 3 tables:

    1. People
    2. Colors
    3. Link table between 1 and 2
    

    I suggest you either fix the problem by utilizing a database or model the thing in Delphi just like it where a database.

    Using Delphi structures
    Furthermore stop using shortstring They are outdated and have zero benefits over longstrings.
    Using 3 tables means you can quickly get a list of people per color and colors per person.

    Here's how it would work:

    TPerson = record
      name: string;
      other_data....
    end;
    
    TPeople = array of TPerson;
    
    TFavColor = record
      name: string;
      other_data....
    end;
    
    TFavColors = array of TFavColor;
    
    TPersonColor = record
      PersonIndex: Cardinal;  <<-- index into the TPeople array
      ColorIndex: Cardinal;   <<-- index into the TFavColors array
    end;
    
    TPersonColors = array of TPersonColor;
    

    Now you can just loop over the TPersonColors array to extract your data.

    Using a database
    In SQL it would be even faster because your data is indexed (foreign key are (should be) always indexed).

    The SQL statement the see all people that like blue and red would look like (using MySQL syntax here):

    SELECT p.name  
    FROM person p
    INNER JOIN personcolor pc ON (pc.person_id = p.id)
    INNER JOIN color c1 ON (pc.color_id = c1.id)
    INNER JOIN color c2 ON (pc.color_id = c2.id)
    WHERE c1.name = 'red' AND c2.name = 'blue'
    GROUP BY p.id <<-- eliminate duplicates (not sure it's needed)
    

    Using Delphi its trivial to link a database to your app.
    So that's the route I'd recommend.

提交回复
热议问题