[تمرين] مولد ارقام عشوائية (RandomGenerator)
#7
هذا حل وليس الامثل
كود :
/////////////////////////////////////////// /////// Random Generator by bo0oda /////// /////// 31-8-2010 /////// //////////////////////////////////////// unit RandomGenerator; interface uses Windows;//only for GetTickCount; type TRandomGenerator = class(TObject) private LastBoolean : Byte;//0:True 1 : False 2:Nothing lastValue : Extended; function RandomNumber(Range : Extended):Extended; public RangeFrom : Extended; RangeTo : Extended; seed: Extended; TruePercnt: Single; Duplicate: Boolean;// defult is fulse = duplicate valuse ; true = non duplicate function Next(): Integer;//Retrieves the next random integer function NextDouble():Extended;//Retrieves the next random Extended function NextBoolean(): Boolean;//Retrieves the next random Boolean constructor Create(); end; implementation constructor TRandomGenerator.Create(); begin RangeFrom:= 0; RangeTo:= 100; lastValue:= 0; TruePercnt:= 50;; lastValue:= 0; LastBoolean:= 2; end; // new mod coz the result of orginal one is integer; function _mod(Dividend,Divisor : Extended):Extended; var quotient: Extended; begin Quotient:= TRunc(Dividend) Div TRunc(Divisor); Result:= Dividend - (Quotient * Divisor) end; // this function to give you random number in your range function TRandomGenerator.RandomNumber(Range : Extended):Extended; var k : Int64; begin if Range <> 0 then //Checking if range != 0 begin // set seed first if seed = 0 then seed:= GetTickCount; //Math Operation try Result:= seed * 65536*1989.0115+0.1028 ; Result:= _mod(Result,Range); while Duplicate and (Result = lastValue) do begin Result:= seed * 65536*1989.0115+0.1028 ; Result:= _mod(Result,Range); seed:= (seed * seed) + 1; end; except Result:= Range-1; end; lastValue:= Result; seed:= lastValue; end else Result:= 0; //if range = 0; end; function TRandomGenerator.NextDouble(): Extended; begin If RangeFrom > RangeTo then Result:= RandomNumber(RangeFrom - RangeTo) + RangeTo else REsult:= RandomNumber(RangeTo- RangeFrom) + RangeFrom ; end; function TRandomGenerator.Next(): Integer; begin If RangeFrom > RangeTo then Result:= Trunc(RandomNumber(RangeFrom - RangeTo) + RangeTo) else REsult:= Trunc(RandomNumber(RangeTo- RangeFrom) + RangeFrom) ; end; function TRandomGenerator.NextBoolean(): Boolean; var P: Single; begin if Duplicate and (LastBoolean <>2)then begin case LastBoolean of 0:begin Result:= False; LastBoolean:= 1; end; 1:begin Result:= True; LastBoolean:= 0; end; end; end else begin P:= RandomNumber(100); Result := p < TruePercnt; if Result then LastBoolean:= 0 else LastBoolean:= 1; end; end; end.
الرد


الردود في هذا الموضوع
[تمرين] مولد ارقام عشوائية (RandomGenerator) - بواسطة bo0oda - 08-10-2010, 06:02 PM

التنقل السريع :


يقوم بقرائة الموضوع: بالاضافة الى ( 1 ) ضيف كريم