A
A
Alex Alex2015-09-09 12:10:09
Delphi
Alex Alex, 2015-09-09 12:10:09

What is the best way to check for a blacklist?

msg:='Загрузили '+inttostr(ids.Count)+' id''s';
 Synchronize(memoadd);
 for i:=0 to ids.Count-1 do begin
 if blackids.Count>1 then begin
   for w:=0 to blackids.Count-1 do begin
     if Pos(ids[i],blackids[w])<>0 then begin
     msg:='Пользователь с id'+ids[i]+' в черном списке';
     Synchronize(memoadd);
     goto next;
     end;
   end;
 end else begin
 end;

A list of ids from 1 to 1000 is loaded into the string list (ids)...
In the string list (blackids) are those ids that were used in the program.
What is the best way to check ids for blackids. When ids=1000 and blackids=5000 , it takes a long time to check...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Z
zed, 2015-09-09
@zedxxx

The initial list must be sorted, and then searched through it not by blunt enumeration, but by binary search:

var
  MyList: TStringList;
  Index: Integer;
begin
  MyList := TStringList.Create;
  try
    MyList.Add('id1');
    MyList.Add('id2');
    MyList.Add('id3');
    MyList.Sort;   { Find will only work on sorted lists! }
    if MyList.Find('id3', Index) then
    begin
      ListBox1.Items.AddStrings(MyList);
      Label1.Caption := 'id3 has an index value of ' + IntToStr(Index);
    end;
  finally
    MyList.Free;
  end;
end;

PS You can also use TDictionary or THashedStringList - the search will be even faster there.

R
Roman Mirilaczvili, 2015-09-09
@2ord

What for for each element of the list to check N^2 times?
Reading about linear search
In general, for an array A, it looks like this:

i := 0;
while (i < N) and (A[i] <> x) do
  inc(i);

Установить i := 0
Цикл i пока список закончился или искомый элемент не соответствует данному из списка
  увеличивать i
Конец цикла
Если i не больше чем количество элементов списка, то найден в списке. // msg:='Пользователь с id'+ids[i]+' в черном списке';
Иначе - не найден.

And, in general, you should think about using SQLite.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question