Jump to content

Random String Generation?


random1

Recommended Posts

This forum is to get help with code you have written. have you even attempted this?

 

Yeah I attempted it using mt_rand like voip03 did, but his is far more elegant. I'll get started on this now :D

 

Well, it will get somewhat complicated (or inefficient) to use that logic while enforcing the requirement for no repeating characters. I have a fairly easy implementation in mind, but I want to at least see you make an attempt rather than just writing it for you.

Link to comment
Share on other sites

Here's a hint - using an array and shuffle() will make things easy. array_slice() can be used to get only part of an array. range() can be used to generate a range of ASCII characters into an array.

 

That's your solution. Give an attempt to code it and we'll help further.

Link to comment
Share on other sites

I ended up using:

 

function rand_str($len, $norepeat = true)
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
$max = strlen($chars) - 1;

if($norepeat && $len > $max + 1)
{
	throw new Exception('Non repetitive random string can\'t be longer than charset');
}

$rand_chars = array();

while($len)
{
	$picked = $chars[mt_rand(0, $max)];

	if($norepeat)
	{
		if(!array_key_exists($picked, $rand_chars))
		{
			$rand_chars[$picked] = true;
			$len--;
		}
	}
	else
	{
		$rand_chars[] = $picked;
		$len--;
	}
}

return implode('', $norepeat ? array_keys($rand_chars) : $rand_chars);   
}

echo rand_str(32, true);

 

Sample output: bkWfyRME%qYHncUF$BjgPLxei5JdSmGs

 

I'll test it more but I'm rather happy with it  :D

Link to comment
Share on other sites

OK, now that you have at least attempted it, I'll show you a more efficient method. You should avoid using loops for things when there are other methods at your disposal. That function is inefficient as it need to run a loop for each and every character - especially since it has to repeat whenever a duplicate character is encountered. That is just a waste.

 

Also, I would suggest not using variable names such as "$norepeat" - when the value is FALSE you have a double negative (by virtue of the no) which results in a true. If a variable is supposed to be true/false, name it such that it is more logical (i.e. $repeat). You can always check for a negative.

 

lastly, I would suggest making the list of characters as an additional parameter for the function. That give's you more flexibility.

 

Anyway, this will do the same thing in a much more efficient manner

function randomString($length, $charList, $repeat=false)
{
if(!$repeat && $length>strlen($charList))
{
	throw new Exception('Non repetitive random string can\'t be longer than charset');
    }
    //Create an array of the characters (add additional if needed)
    $charsAry = str_split(str_repeat($charList, ceil($length/strlen($charList))));
    //Randomize the array
    shuffle($charsAry);
    //Return the random string
    return implode(array_slice($charsAry, 0, $length));
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
echo randomString(32, $chars);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.