Given a size N and the task is to generate a random string of size N.
Examples:
Input: 5
Output: eR3Ds
Input: 10
Output: MPRCyBgdcn
Method: Create a domain string which contains small letters, capital letters and the digits (0 to 9). Then generate a random number and pick the character present at that random index and append that character into the answer string.
Below is the program to generate random string using above method:
<?php
function RandomStringGenerator( $n )
{
$generated_string = "" ;
$domain = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" ;
$len = strlen ( $domain );
for ( $i = 0; $i < $n ; $i ++)
{
$index = rand(0, $len - 1);
$generated_string = $generated_string . $domain [ $index ];
}
return $generated_string ;
}
$n = 5;
echo "Random String of length " . $n
. " = " . RandomStringGenerator( $n );
?>
|
Output:
Random String of length 5 = EEEto