[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
Solved

# My rendom gen function problem ?

Posted on 2006-05-16
Medium Priority
176 Views
I have writtern the folowing function

function RandGen(option : integer; aWordLen : integer) : string;
var
aSRC, LettersNumbers, Letters, Numbers : string;
begin

LettersNumbers := 'abcdefghijklmnoprstuvzyxwqABCDEFGHIJKLMNOPRSTUVZXYQW1234567890';
Letters := 'abcdefghijklmnoprstuvzyxwqABCDEFGHIJKLMNOPRSTUVZXYQW';
Numbers := '1234567890';

if option = 1 then aSRC := LettersNumbers;
if option = 2 then aSRC := Letters;
if option = 3 then aSRC := Numbers;

result := '';

while Length(result) <= aWordLen do
result := result + aSRC[Random(Length(aSRC))];

end;

And i'm calling this function from loop which will repeat 20 times like this
var := varP + RandGen(2, Random(5) + 5) + RandGen(3, Random(3));
var2 :=  RandGen(1, Random(4) + 6);

So my program need to genrete for example 20 strings, but when it generetes  1 or 2 or 5 or... i get error. "Index was outside the bounds of the array."

Can you tell me what is the problem and fix the code.

Thank you !
0
Question by:65zgtre45rr

LVL 26

Accepted Solution

Russell Libby earned 1400 total points
ID: 16695540
Random returns a number from 0 to Range-1, and if it returns back zero on you, it will error (string index is from 1 to length). So change the following:

result := result + aSRC[Random(Length(aSRC))+1];

Regards,
Russell

0

Assisted Solution

djConex earned 600 total points
ID: 16696474
rllibby is correct.
but however i made a another way most simple to do the same thing.

function RandGen(option : integer; aWordLen : integer) : string;
var
x : integer;
begin
result := '';  //clear result
case option of
1 : begin //Letters and numbers
for x := 1 to awordlen do
case random(3) of
0: result := result+                char(randomrange(ord('a'),ord('z')+1));
1: result := result+uppercase(char(randomrange(ord('a'),ord('z')+1)));
2: result := result+                char(randomrange(ord('0'),ord('9')+1));
end;
end;

2 : begin //Letters
for x := 1 to awordlen do
case random(2) of
0:  result := result+                char(randomrange(ord('a'),ord('z')+1));
1:  result := result+uppercase(char(randomrange(ord('a'),ord('z')+1)));
end;
end;

3 : begin //numbers
for x := 1 to awordlen do
result := result+char(randomrange(ord('0'),ord('9')+1));
end;
end; // end of case
end;
0

Author Comment

ID: 16701434
This is not neded rllibby's solution works.

Thank you !
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question