Recently, due to some of the reasons for the company has to re-enter the tide of job hunting. In the interview process also encountered some more interesting face questions. may not have thought at that time, came back after thinking again. Topic One: A known user ID (ID is long shaping) generates a unique invitation code (invitation code range ([a-z0-9]) for the user based on the user ID. Code implementation.
Several of the options at the time were simple:
<?php
function Createcode ($userId)
{
//Scenario One:
$currentTime = time ();
$code = "{$userId} {$currentTime}";
return $code;
Scenario Two: While
(true) {
//Get a random string
$code = getrandstring (8);
Determine if the string exists if
(! checkexists ($code)) return
$code
}
}
Several of the options that came to mind at the time were evolving in the same way.
Disadvantages of both schemes:
Scheme One: string length is too long, the invitation code is generally required to pass between the user. Too long is not conducive to the user to remember. And not elegant. Oh.
Scenario Two: Every time a random string is generated, it needs to go to the database to find out if it already exists. When the user base is large, it is bound to affect efficiency. For the developer who pursues efficiency. Such schemes are not the best.
The new scheme:
The character a-z0-9 is just 36. Can you consider converting a user ID directly into a 36-digit number?
Code implementation:
<?php
function Createcode ($userId)
{
static $sourceString = [
0,1,2,3,4,5,6,7,8,9,10, '
a ', ' B ', ' C ', ' d ', ' e ', ' f ',
' g ', ' h ', ' I ', ' j ', ' K ', ' l ', '
m ', ' n ', ' o ', ' P ', ' Q ', ' R ', '
s ', ' t ', ' u ', ' V ', ' w ', ' X ',
' y ', ' z '
];
$num = $userId;
$code = ';
while ($num)
{
$mod = $num%;
$num = (int) ($num/36);
$code = "{$sourceString [$mod]}{$code}";
}
Judge the length of the code
if (Empty ($code [4]))
Str_pad ($code, 5, ' 0 ', str_pad_left);
return $code;
}
Compared with the first two schemes, the new scheme makes up for the disadvantages of the first two schemes, while ensuring the same user's advantages of repeating the invitation code, of course, the implementation needs to be treated in a specific way.