-3

在帕斯卡中,我想随机选择一个 1 到 50 之间的数字,它会进入一个循环。每次选择一个数字时,都会删除该数字,直到最终没有 1 到 50 之间的数字可供选择,循环结束。

在 Pascal/Delphi 中是如何完成这样的事情的?

4

1 回答 1

5

这一定很容易。

  1. 您从 1 到 50 的数字数组开始
  2. 在每次迭代中,您选择一个介于 1 和数组元素数之间的随机数
  3. 你从数组中取出那个元素
  4. 转到第 2 步,直到数组中没有更多元素为止。

在代码中,它可能如下所示:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

const
  ARRAY_ELEMENTS = 50;

var
  SourceArray: array of Integer;
  Element: Integer;
  ValidElements: Integer;
begin
  Randomize;
  try
    //array initialization
    SetLength(SourceArray, ARRAY_ELEMENTS);
    for Element := Low(SourceArray) to High(SourceArray) do
      SourceArray[Element] := Element + 1;
    ValidElements := ARRAY_ELEMENTS;
    repeat
      //select a random element
      Element := Random(ValidElements);
      Writeln(SourceArray[Element]);
      //remove the element from the array
      SourceArray[Element] := SourceArray[ValidElements - 1];
      Dec(ValidElements);
    until ValidElements = 0;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.

在评论后进行编辑,通过将最后一个数组元素与戳过的元素交换来提高性能。

列表示例

我没有注意到您的标签,所以这是一个列表示例:

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  Generics.Collections;

const
  LIST_ELEMENTS = 50;

var
  I: Integer;
  Element: Integer;
  SourceList: TList<Integer>;
begin
  Randomize;
  try
    SourceList := TList<Integer>.Create();
    try
      for I := 1 to LIST_ELEMENTS do
        SourceList.Add(I);
      repeat
        Element := Random(SourceList.Count);
        Writeln(SourceList[Element]);
        SourceList.Delete(Element);
      until SourceList.Count = 0;
    finally
      SourceList.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.
于 2013-03-08T05:53:39.230 回答