I create a random string of a given length with the function below:
function generateRandomString($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
}
This gives me a result of e.g. aBcDEFghIJKlmNo
when giving it 15 as length.
Now I also have a variable number that can go from say 1 to 10.000.000. Let us say the number is 12.345 for simplicity, but the solution needs to work for any number in the range.
I need a function that takes this number 12.345 and puts the numbers consecutively into the string aBcDEFghIJKlmNo
at random places, giving a result of e.g. ‘a1BcD23EFg4hIJ5KlmNo’.
function placeNumberInString($string, $number){
$new_string = '';
// I can't figure out what to do here...
return $new_string;
}
$result = placeNumberInString(aBcDEFghIJKlmNo, 12345);
echo $result;
3
Answers
You can split the string at random index starting at the last index and insert the number
This is essentially a single iteration of a classic riffle shuffle between a
aBcDEFghIJKlmNo
stack and a12345
stack. Usestr_split()
to split each stack into arrays, so that you have this:Then implement the shuffle on those two arrays:
Something like:
If you want to preserve the order of the digits in the number, you could just build up the new string a bit at a time.