Skip to content

Searching for Bobby Fisher

Special thanks to puzzle regular Roddy Pratt for suggesting the idea for this week's puzzle.

Roddy (*Names may have been changed to protect the innocent) had code similar to the following:

  1. function FindBobbyFisher: Integer;
  2. var
  3.   Names: TStringList;
  4.   I: Integer;
  5. begin
  6.   Names := TStringList.Create;
  7.   Names.LoadFromFile('names.txt');
  8.   if not Names.Find('Bobby Fisher', I) then
  9.     Result := -1
  10.   else
  11.     Result := I;
  12.   Names.Free
  13. end;

Roddy's code worked at first, but soon Bobby Fisher could not be found. What is Roddy missing?

2 Comments

  1. Rcus wrote:

    Find method of TStringList works only for sorted lists (cause of binary search algorythm that has O(log(N)) complexity), in case of unsorted lists its result isn’t defined. By default TStringList isn’t sorted but you can do it by calling Sort method (underlying algorythm of quicksort has O(N*log(N))) complexity). If you don’t need to search many times IndexOf method will be faster (N complexity but works for any lists).

    Monday, April 14, 2008 at 2:29 am | Permalink
  2. Yes the Delphi help says:

    Find will only work on sorted lists!

    Therefore Names.Sort; should be added after the LoadFromFile call.

    Monday, April 14, 2008 at 8:31 am | Permalink

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*