一个随机序列的实现问题(100分)

  • 主题发起人 主题发起人 delphilike
  • 开始时间 开始时间
D

delphilike

Unregistered / Unconfirmed
GUEST, unregistred user!
我在使用matlab编程,需要随机产生一个随机序列<br>但是找遍所有资料也没有发现这样一个函数,只能投靠于delphi拉<br>我的问题是:<br>&nbsp; &nbsp;如何把8,7,6,5,4,3,2,1,0这9个数字组合成一个9位的随机<br>&nbsp; &nbsp;序列如:872465103,154326870。。。。。。也就是说这9个数字都<br>&nbsp; &nbsp;不会重复,产生任一个序列每个数字只用一次。<br>不知道该如何实现,还请高手赐教,谢谢
 
function Answer:String;<br>const<br>&nbsp; S:String='0123456789';<br>var<br>&nbsp; T:String;<br>&nbsp; K:Integer;<br>begin<br>&nbsp; Randomize;<br>&nbsp; while Length(S)&gt;0 do<br>&nbsp; begin<br>&nbsp; &nbsp; K:=Random(Length(S))+1;<br>&nbsp; &nbsp; T:=T+S[K];<br>&nbsp; &nbsp; Delete(S,K,1);<br>&nbsp; end;<br>&nbsp; Result:=T;<br>end;<br><br>&nbsp; &nbsp;
 
其实就是一个random函数.
 
这个问题可以这样来实现:<br><br>var<br>&nbsp;a :array[0..8] of Byte;<br>&nbsp;i, p, q, temp:Byte;<br>begin<br>&nbsp;randomize;<br>&nbsp;for i :=0 to 8 do a ;=i;<br>&nbsp;for i :0 to 8*3 do<br>&nbsp; begin<br>&nbsp; &nbsp;p ;=random(9);<br>&nbsp; &nbsp;q :=random(9);<br>&nbsp; &nbsp;temp :=a[p];<br>&nbsp; &nbsp;a[p] :=a[q];<br>&nbsp; &nbsp;a[q] ;=temp;<br>&nbsp; end;<br>end; &nbsp; <br>
 
procedure TForm1.Button1Click(Sender: TObject);<br>var<br>&nbsp; sConst:string;<br>&nbsp; sOut :string;<br>&nbsp; i,iPos:integer;<br>begin<br>&nbsp; sConst := '012345678';<br><br>&nbsp; for i := 9 downto 1 do<br>&nbsp; begin<br>&nbsp; &nbsp; iPos := integer(random(i));<br>&nbsp; &nbsp; if(iPos = 0) then iPos := i;<br>&nbsp; &nbsp; sOut := sOut + sConst[iPos];<br>&nbsp; &nbsp; Delete(sConst,iPos,1);<br>&nbsp; end;<br>&nbsp; ShowMessage(sOut);<br>end;<br><br>procedure TForm1.FormCreate(Sender: TObject);<br>begin<br>&nbsp; //这里最好根据时间来定RandSeed<br>&nbsp; RandSeed := 1999;<br>&nbsp; Randomize;<br>end;<br>
 
一不留神,前面已经有了这么多例子,早知道就不贴了。
 
sorry!<br>刚才有些地方有错。<br>var<br>&nbsp;a :array[0..8] of Byte; <br>&nbsp;i, p, q, temp: Byte;<br>begin <br>&nbsp;randomize;<br>&nbsp;for i :=0 to 8 do a :=i; <br>&nbsp;for i :=0 to 8*3 do &nbsp;<br>&nbsp; &nbsp;begin &nbsp; <br>&nbsp; &nbsp; p :=random(9);<br>&nbsp; &nbsp; q :=random(9); &nbsp; <br>&nbsp; &nbsp; temp :=a[p]; &nbsp; <br>&nbsp; &nbsp; a[p] :=a[q]; &nbsp; <br>&nbsp; &nbsp; a[q] :=temp; &nbsp;<br>&nbsp; end;<br>end; &nbsp; <br>其实就是洗牌吗!
 
后退
顶部