1. Computing & Technology

Discuss in my forum

Kaushalya Damitha Weerakoon's Entry for the Unique Random Numbers Generator

By , About.com Guide

Question: Kaushalya Damitha Weerakoon'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 Kaushalya Damitha Weerakoon (Sri Lanka):
 procedure Randomizer_Kaushalya_Damitha_Weerakoon(const maxValue : int64; var values : array of int64) ;
 var
   cnt: int64;
   Rand,EndV:Int64;
   MyMax : Integer;
   arr : Array of Boolean;
 begin
   Randomize;
   MyMax := Trunc(sqrt(maxvalue)) + 1;
   Setlength(arr,MaxValue) ;
 
   cnt := 0;
   EndV := Length(Values)-1;
   repeat
     repeat
       repeat
         Rand := Random(MyMax)*Random(MyMax) + 1;
       until (rand <= maxValue) ;
     until not arr[rand];
 
     arr[rand] := True;
     Values[cnt] := Rand;
     inc(cnt) ;
   until cnt >= EndV;
 
   arr := nil;
 end;
 
Test data:
- array size: 10 000
- number range: 1 - 100 000

Kaushalya's speed result: 860 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.