1. Computing & Technology

Discuss in my forum

David Reed's Entry for the Unique Random Numbers Generator

By , About.com Guide

Question: David Reed'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 David Reed (USA):
 procedure Randomizer_David_Reed(const maxValue : int64; var values : array of int64) ;
 var
   x,y,xVal,xLen: integer;
   a: array of int64;
 begin
   xLen := Length(values) ;
   xVal := maxValue div xLen;
   SetLength(a,xLen) ;
   // Generate a set of unique sorted random numbers..
   for x := 0 to xLen - 1 do
     a[x] := (xVal * x) + Random(xVal) + 1;
   // Randomly assign the random unique values to
   // the values array..
   for x := xLen - 1 downto 0 do begin
     y := Random(x) ;
     values[x] := a[y];
     a[y] := a[x];
   end;
 end;
 

Test data:
- array size: 10 000
- number range: 1 - 100 000

David's speed result: 370 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.