1. Computing & Technology

Discuss in my forum

Jim Murtha's Entry for the Unique Random Numbers Generator

By , About.com Guide

Question: Jim Murtha's Entry for the Unique Random Numbers Generator
Challenge: a custom Delphi function, Randomizer, takes an open integer array and should fill it with unique random numbers as fast as possible.

The code is submitted for the Unique Random Numbers Delphi Challenge

Answer: Unique random number generator entry by Jim Murtha (USA):
 procedure Randomizer_Jim_Murtha(const MaxValue : Int64; var Values : Array of Int64) ;
 var Counter, Number, Keep, Limit : Int64;
     Valid : Boolean;
     Tmp : Array of Int64;
 begin
   // Size and zero out temp array.
   SetLength(Tmp,MaxValue + 1) ;
   Counter := 0;
   while Counter <= MaxValue do
   begin
     Tmp[Counter] := 0;
     Counter := Counter + 1;
   end;
   // Fill temp array with a 1 in all slots
   // selected by the random number.
   // If array slot is already 1, pick
   // another random number.
   Limit := Length(Values) ;
   Counter := 0;
   while Counter < Limit do
   begin
   Valid := False;
   while not(Valid) do
     begin
     Number := Random(MaxValue) + 1;
     if Tmp[Number] = 0 then
     begin
       Tmp[Number] := 1;
       Valid := True;
       Counter := Counter + 1;
     end;
     end;
   end;
   // Go through temp array and put the
   // selected numbers into the 'Values' array.
   Counter := 1;
   Keep := -1;
   while Counter <= MaxValue do
   begin
   if Tmp[Counter] = 1 then
     begin
       Keep := Keep + 1;
       Values[Keep] := Counter;
     end;
     Counter := Counter + 1;
   end;
   Tmp := nil;
 end;
 
Test data:
- array size: 10 000
- number range: 1 - 100 000

Jim's speed result: 3 600 microseconds.

Explore the list of all accepted entries for the Fastest Unique Random Number Generator Delphi challenge.

Readers Respond: Your Delphi Programming Challenges

©2012 About.com. All rights reserved.

A part of The New York Times Company.