use*_*260 -2 delphi pascal list
在pascal中,我想随机选择1到50之间的循环数.每次选择一个数字时,该数字将被删除,直到最终在1到50之间没有数字可供选择并且循环结束.
如何在Pascal/Delphi中完成这样的事情?
这必须非常简单.
在代码中,它看起来像这样:
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.
Run Code Online (Sandbox Code Playgroud)
在注释后编辑,通过将最后一个数组元素与poked一个数组交换来提高性能.
我没有注意到你的列表标签,所以这是一个列表示例:
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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
635 次 |
| 最近记录: |