假設有一組數字 1~1000,請將它們隨機填充在一個數組中
要求:
1、數組中無重復數字
2、整個程式運算很快!
william 兄解答
var
Nums: array[1..1000] of integer;
i,j,k,temp: integer;
begin
for i := Low(Nums) to High(Nums) do
Nums[i] := i;
for i := 0 to 1000 do begin // 1001 round may not be enough
j := random(High(Nums))+1;
k := random(High(Nums))+1;
temp := Nums[j];
Nums[j] := Nums[k];
Nums[k] := temp;
end;
end;Fishman 兄解答
我有一些新的想法,與大家共同分享、討論
procedure TForm1.Button11Click(Sender: TObject); VAR I,R : Integer; S : TStrings; begin ListBox1.Items.Clear; for i := 1 to 1000 do begin ListBox1.Items.Add(IntToStr(I)); end; S := TStringList.Create; S.Assign(ListBox1.Items); ListBox2.Items.Clear; FOR I := 1000 DOWNTO 1 DO BEGIN R := Random(I) + 1; ListBox2.Items.Add(S.Strings[R - 1]); S.Delete(R - 1); END; S.Free; end;
在此我用ListBox 來代替 Array,以方便直接觀看執行結果
![]()
--------------------------------
小弟才疏學湥粲兄囌`請不吝指教
--------------------------------