php password generating function
Here is a question i want to solve
"Write a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9).
When GeneratePassword(5,'abc0123') is called, it should return a random string of 5 characters taken from 'abc0123'.
For Example : GeneratePassword(7,'abczxc012394') could return any of the following outputs : 2c00acb 2c23z93 030b2a4 "
I have written the following code for it, but the system says that the answer is wrong. Please explain what am i doing wrong.
My code :
function GeneratePassword($digits,$passwordString){
if($digits > strlen($passwordString)) return '';
else {
$randomSelect = '';
for($i=0;$i<$digits;$i++){
$randomChar = $passwordString[rand(0, strlen($passwordString)-1)];
$random开发者_JAVA技巧Select = $randomSelect.$randomChar ;
$passwordString = str_replace($randomChar,"",$passwordString);
}
return $randomSelect;
}
}
Firstly, you shouldn't reject $digits
being higher than the number of characters to choose from. You could easily receive GeneratePassword(10,'A')
, in which case you'd need to return AAAAAAAAAA
.
Second, you shouldn't remove selected characters from the string. The examples even include duplicate characters (2c00acb
for instance).
Apart from that, your code seems to work. I would suggest, though, that you calculate strlen($passwordString)
up front and save it in a variable, rather than computing it once for every iteration of the loop.
function GeneratePassword($length,$characters) {
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo GeneratePassword(7, 'abczxc012394');
Here's the version I would make. Mind you that I've replaced "$digits" with "$length", because, well, that's what it's supposed to indicate. Also, I've replaced "$passwordString" with the more commonly accepted term "$seed". Explanation is inline.
function GeneratePassword( $length, $seed ) {
$password = ''; /** Begin with an empty string. */
$max = ( $length - 1 ); /** Calculate the number of characters in seed -1, because strings are zero-indexed. */
for( $i = 0; $i < $length; $i ++ ) { /** Loop until the maximum length is reached. */
$password .= $seed[mt_rand( 0, $max )]; /** Select a random character and append it to the password string. */
}
return $password; /** return the password */
}
function GeneratePassword($digits,$passwordString){
$randomSelect = '';
for($i=0;$i<$digits;$i++){
$randomChar = $passwordString[rand(0, strlen($passwordString)-1)];
$randomSelect = $randomSelect.$randomChar ;
$passwordString = str_replace($randomChar,"",$passwordString);
}
return $randomSelect;
}
you should reuse the chars in $passwordString
function GeneratePassword($n,$c){
$pw = '';
for ($l = 0; $l < $n; $l++){
$r = rand(0, strlen($c) - 1);
$pw .= $c[$r];
}
return $pw;
}
精彩评论