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)];
$randomSelect = $randomSelect.$randomChar ;
$passwordString = str_replace($randomChar,"",$passwordString);
}
return $randomSelect;
}
}
Firstly, you shouldn’t reject
$digitsbeing higher than the number of characters to choose from. You could easily receiveGeneratePassword(10,'A'), in which case you’d need to returnAAAAAAAAAA.Second, you shouldn’t remove selected characters from the string. The examples even include duplicate characters (
2c00acbfor 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.