Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Random numbers for Cris .B

Title: Random numbers for Cris .B Question: I want to select for example 20 entries at random,from the database,it must give me a different set of numbers every time. ( The application i am creating is a question & Answer Database, the Instructor needs to select for instance 20 Question from the database at random.) Please Help me Answer: I want to select for example 20 entries at random,from the database,it must give me a different set of numbers every time. ( The application i am creating is a question & Answer Database, the Instructor needs to select for instance 20 Question from the database at random.) Please Help me ok so u want 20 diferent entrys each time right i assuming that u use the Ids of the Question records in the Database Build a array of those records like this Form1 = Class(TForm) Public GetNextNumObject : Array of integer ; Lastget : Integer ; // Call at forms create or forms show ; Procedure Init ; Function GetQueryInString : String ; Procedure GetNext20 ; end; Procedure TForm1.GetNext20 ; begin SomeQuery.Close ; // This wil look like 'Select * from question where id in (7,2,16,76,4,3,enz)' ; SomeQuery.sql.text := Format('Select * from question where id in (%s)' ,GetQueryInString]) ; SomeQuery.open ; end; Procedure TForm1.Init ; var I,Temp,Random1,Random2 : Integer ; begin i := 0 ; SomeQuery.sql.text := 'Select ID from question'; SomeQuery.open ; // if u now record count init the arraya here // SetLength(GetNextNumObject.ANumberArray,SomeQuery.recordCount) ; // if not use Setlength everytime While not SomeQuery.eof do begin inc(i); SetLength(GetNextNumObject.ANumberArray,i); GetNextNumObject[i-1] := SomeQuery.Fields[0].asinteger ; SomeQuery.NEXT; end; Randomize ; // Shuffel the data For i := 0 to 10000 do begin Random1 := Random(High(GetNextNumObject)) ; Random2 := Random(High(GetNextNumObject)) Temp := GetNextNumObject[Random1] ; GetNextNumObject[Random1] := GetNextNumObject[Random2] ; GetNextNumObject[Random2] := Temp ; end; end; Function TForm1.GetQueryInString : String ; var i : Integer ; begin // do we stil have 20 left ? if no do init again If LastGet + 20 High(GetNextNumObject) then begin Init ; LastGet := 0 ; end; for i := lastget to lastget + 20 do begin Result := Result ',' + IntToStr(GetNextNumObject[i]); end; If result '' then Result[1] := ' ' ; Trim(Result); Inc(LastGet,20); end;