I want to generate random number with specified length.
function _RandomCode(const CodeLen: Word): Word;
begin
Result := Random(CodeLen);
repeat
Result := Result + Random(CodeLen) + 1;
until (Length(IntToStr(Result)) = CodeLen)
end;
The result always 10000
Although I voted to close this question as a duplicate, on a second thought here are aspects that makes it different from a pure random function application.
First, your code doesn't give you the result you are expecting because you are adding small numbers (0 .. codelen-1) to the result for each loop, stopping when the value reaches a value that, when converted to string, contains the codelen number of characters. For a codelen = 5 this will always stop at 10000 .. 10003. If you would have stepped through the code in the debugger, you would soon have realized why you got the result you did.
Secondly, inspired by @MichaelVincent, a PIN code usually allows leading zeros, f.ex. '0123'. I therefore assume this to be the case in this question too. Because an integer type result can not hold leading zeros, I suggest you use a string type result.
Call Randomize once only at startup of your application.
function _RandomCodeStr(const CodeLen: Word): string;
var
n: integer;
begin
SetLength(Result, CodeLen);
for n := 1 to CodeLen do
Result[n] := Char(ord('0')+ Random(10));
end;
I changed the name of the function to reflect that it returns a string.
Addition on request:
Regarding the Randomize function (or assigning RandSeed). It is explained in the documentation:
Randomize initializes the built-in random number generator with a random value (obtained from the system clock). The random number generator should be initialized by making a call to Randomize, or by assigning a value to RandSeed.
Do not combine the call to Randomize in a loop with calls to the Random function. Typically, Randomize is called only once, before all calls to Random.
If you put the _RandomCodeStr function in a separate unit, you can put the call to Randomize in that units initialization section.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With