Hi I am trying to generate three random characters using a function in Delphi, the code is this:
function generate(cantidad: integer): string;
const
letras_mi = 'abcdefghijklmnopqrstuvwxyz';
const
letras_ma = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const
numeros = '0123456789';
var
finalr: string;
begin
finalr := '';
finalr := finalr + IntToStr(Random(Length(letras_mi)) + 1);
finalr := finalr + IntToStr(Random(Length(letras_ma)) + 1);
finalr := finalr + IntToStr(Random(Length(numeros)) + 1);
Result := finalr;
end;
the problem is that things like 20142 me back when I'm actually waiting 3 characters constant random variables.
function RandomString(const ALength: Integer): String;
var
i: Integer;
LCharType: Integer;
begin
Result := '';
for i := 1 to ALength do
begin
LCharType := Random(3);
case LCharType of
0: Result := Result + Chr(ord('a') + Random(26));
1: Result := Result + Chr(ord('A') + Random(26));
2: Result := Result + Chr(ord('0') + Random(10));
end;
end;
end;
Your code is converting integer index values to strings. Note that your only reference to your constants is to take their length. You return indices rather than characters.
You could fix your code by using the integer indices you generate to reference elements within your string constants. Mason and Ken showed how to do that.
Personally I would do away with the constants and write
Chr(ord('a') + Random(26))
and
Chr(ord('A') + Random(26))
and
Chr(ord('0') + Random(10))
The ordinal values of these characters were designed way back when to allow such code.
You're adding the result of Random
to your finalr
, not the random letter from the constants.
Try something like this instead - it uses the return of Random
as the index into the string constant characters:
function generate(cantidad: integer): string;
const
letras_mi = 'abcdefghijklmnopqrstuvwxyz';
letras_ma = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
numeros = '0123456789';
begin
Result := '';
Result := Result + letras_mi[Random(Length(letras_mi)) + 1];
Result := Result + letras_ma[Random(Length(letras_ma)) + 1];
Result := Result + numeros[Random(Length(numeros)) + 1];
end;
Let's look at what your code is doing, as a compiler sees it:
IntToStr(Random(Length(letras_mi)) + 1)
Call IntToStr on the result of:
Call Random on the result of:
Add
Length(letras_mi)
1
IntToStr takes a number (such as 5
) and turns it into a string (such as '5'
). What you want to do is use the random value to index into your array, like so:
letras_mi[Random(Length(letras_mi)) + 1]
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