2004. szeptember 24., péntek

How to create a random list of numbers


Problem/Question/Abstract:

I should give an example of what I'm trying to do. The NewTrackList procedure is supposed to create a list of 14 numbers from 1 to 14, with no numbers repeated. The list is supposed to be random, that is, a different sequence of numbers is created every time the procedure runs.

Answer:

procedure NewTrackList;
var
  TrackNumbersList: array[1..14] of Integer;
  I, II: Integer;
  SameTracks: Boolean;
  S: string;
begin
  for I := 1 to 14 do
    TrackNumbersList[I] := 0;
  for I := 1 to 14 do
  begin
    TrackNumbersList[I] := Random(14) + 1;
    repeat
      SameTracks := False;
      for II := 1 to I - 1 do
      begin
        if I = 1 then
          Break;
        if TrackNumbersList[I] = TrackNumbersList[II] then
        begin
          SameTracks := True;
          TrackNumbersList[I] := Random(14) + 1;
          Break;
        end;
      end;
    until
      not SameTracks;
  end;
  S := '';
  for I := 1 to 14 do
    S := S + '  ' + IntToStr(TrackNumbersList[I]);
  Form1.Label1.Caption := S;
end;

procedure TTunesMain.FormCreate(Sender: TObject);
begin
  Randomize;
  NewTrackList;
end;

S is a local variable of type String. I obviously added a TLabel to the form, as well.

Nincsenek megjegyzések:

Megjegyzés küldése