1. Computing & Technology

Discuss in my forum

Marius van Loo's Entry for the Unique Random Numbers Generator

By , About.com Guide

Question: Marius van Loo'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 Marius van Loo (Republic of South-Africa):
 procedure Randomizer_Marius_van_Loo(const maxValue : int64; var values : array of int64) ;
 var
   count, num : int64;
   k : integer;
   found : boolean;
 
 begin
   count := -1;
 
   while (count < high(values)) do
   begin
     found := false;
 
     num := randomRange(1,maxValue + 1) ;
 
     for k := 0 to count do
       if (num = values[k]) then
       begin
         found := true;
         break;
       end;
 
     if not(found) then
     begin
       inc(count) ;
       values[count] := num;
     end;
   end;
 end;
 
Test data:
- array size: 10 000
- number range: 1 - 100 000

Marius's speed result: 130 milliseconds.

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.