编写一个函数GeneratePassword,它接受两个参数,一个整数和一个由字母(a-z)和数字(0-9)组成的字符串


Write a function GeneratePassword which accepts two arguments, an integer and a character string consisting of letters (a-z) and digits (0-9)

编写一个函数GeneratePassword,它接受两个参数,一个整数和一个由字母(a-z)和数字(0-9)组成的字符串。

当调用GeneratePassword(5,'abc0123')时,它应该返回一个从"abc0123"中提取的5个字符的随机字符串。

例如:GeneratePassword(7,'abczxc012394')可以返回以下任何输出:

2c00acb
2c23z93
030b2a4

我想你在找作业标签。

本着帮助他人的精神,我将发布一个有评论的解决方案。但是,请记住,变得更好的唯一方法是先尝试,然后再提问。也就是说,尝试一下,然后问别人你哪里出了问题。

示例/演示:

/**
 * Generate a password N characters long consisting of characters
 *
 * @param int $size
 * @param string $characters
 * @param callback $random (optional) source of random, a function with two parameters, from and to
 * @return string|NULL password
 */
function generate_password($size, $characters, $random = 'rand') {
    // validate $size input
    $size = (int) $size;
    if ($size <= 0) {
        trigger_error(sprintf('Can not create a password of size %d. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }
    if ($size > 255) {
        trigger_error(sprintf('Refused to create a password of size %d as this is larger than 255. [%s]', $size, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }
    // normalize $characters input, remove duplicate characters
    $characters = count_chars($characters, 3);
    // validate number of characters
    $length = strlen($characters);
    if ($length < 1) {
        trigger_error(sprintf('Can not create a random password out of %d character(s). [%s]', $length, __FUNCTION__), E_USER_WARNING);
        return NULL;
    }
    // initialize the password result
    $password = str_repeat("'x00", $size);
    // get the number of characters minus one
    // your string of characters actually begins at 0 and ends on the
    // string-length - 1:
    //   $characters[0] = 'a'
    //   $characters[1] = 'b'
    //   $characters[2] = 'c'
    $length--;
    // get one random character per each place in the password
    while ($size--)
    {
        // generate a random number between 0 and $length (including)
        $randomValue = $random(0, $length);
        // that random number is used to turn the number into a character
        $character = $characters[$randomValue];
        // set the random character
        $password[$size] = $character;
    }
    // return the result
    return $password;
}