views:

170

answers:

5

i would like to make a list of names and then make a random selection but all of them should be called. off course not repeated. delphi code

+3  A: 

My suggestion is to make a list of names and then shuffle the name then call it one by one. i hope this code will work for you.

...
  private
    { Private declarations }
    FNameList : TStringList;
    FNameIndex: Integer;
  public
    { Public declarations }
  end;
...

procedure TForm1.FormCreate(Sender: TObject);
var i: Integer;
begin
  Randomize;
  FNameIndex := 0;
  FNameList := Tstringlist.Create;
//  FNameList.LoadFromFile('NameList.txt'); or
  FNameList.Add('Name 1');
  FNameList.Add('Name 2');
  FNameList.Add('Name 3');
  FNameList.Add('Name 4');
  FNameList.Add('Name 5');
  FNameList.Add('Name 6');

  for i:= 1 to 100 do // shuffle 100 times. its up to you
    FNameList.Exchange(Random(FNameList.Count-1), Random(FNameList.Count-1));
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  FNameList.Free;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if FNameIndex < FNameList.Count then
    begin
      showmessage(FNameList.Strings[FNameIndex]);
      inc(FNameIndex);
    end else showmessage('Done!');
end;
XBasic3000
The idea is good - shuffle the list, and then run through it. But your shuffling routine is not good. Rather try something like this: for I := 0 to aList.Count-1 do aList.Exchange(I,randomrange(I,aList.Count));
Svein Bringsli
+2  A: 

Sounds like you want the Fisher–Yates shuffle. Sample code

Jivlain
A: 

Well I can not deliver you delphi code but I have quite the same problem here. I am using a list of Names (with addresses) from this website http://de.fakenamegenerator.com.

Maybe it's a little help.

Yves M.
A: 

I'm not into delphi, but the algorithm is quite straightforwarded. Just insert names into a List with a random generated index. This way you have a randomly sorted List of names. Then just iterate over it.

Jeroen Rosenberg
yah that what i did, but if i use random(Index) there is posible repeated Index
XBasic3000
So check if the list element is empty first before inserting. If not empty then generate a new random index.
No'am Newman
A: 

Make a copy of the names into List and execute the following:

// assuming list is a stringlist containing the names
while List.Count > 0 do begin
  idx := Random(List.Count);
  // do something with List[idx]
  List.Delete(idx);
end;
Uwe Raabe