Page 1 of 1

code to get permutations

Posted: Thu Dec 20, 2007 11:21 pm
by s.dot

Code: Select all

$chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
I can't seem to figure out how to get all the possible 6 character combinations with or without repeating characters. Any help here?

Posted: Fri Dec 21, 2007 3:13 am
by onion2k
Isn't that going to be 62^6 different possibilities ... 56,800,235,584 6 character strings ... What on Earth are you doing?

Posted: Fri Dec 21, 2007 3:32 am
by s.dot
onion2k wrote:Isn't that going to be 62^6 different possibilities ... 56,800,235,584 6 character strings ... What on Earth are you doing?
Using this as a unique identifier for a database row. Incremented numbers are too easily guessable. Not that it's a security issue, but I'd rather someone not view all content by simply incrementing the id in the address bar. :)

Much like youtube.. I suppose. Where the url will be something like view.php?id=aX8Dd1

Posted: Fri Dec 21, 2007 3:39 am
by bokehman
onion2k wrote:Isn't that going to be 62^6 different possibilities ... 56,800,235,584 6 character strings ... What on Earth are you doing?
Not if you are just after combinations, but it's still a big number.

Scotty, your best bet is a lazy iterator. Have a look at http://www.tagarga.com/blok/on/070910

Posted: Fri Dec 21, 2007 3:40 am
by onion2k
In which case you don't need all the possibilities. Just generate a random one and check it hasn't been used. If it has, generate another one until you get one that's not been taken.

Posted: Fri Dec 21, 2007 4:01 am
by s.dot
@bokehman - Thanks, that looks like a nifty little snippet.

@onion2k - You're right, I don't need ALL of them. However doing what you suggested at runtime seems like a bit too much overhead. I can pregenerate a list of a couple million and store it in the database, then delete from the list once it's assigned. This way I'll only need one query.. every time.

Something like the following did the trick for me

Code: Select all

$chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));

$it = 0;
$strings = array();
while ($it < 3000000)
{
    shuffle($chars);
    $strings[] = $chars[0] . $chars[1] . $chars[2] . $chars[3] . $chars[4] . $chars[5];
    $it++;
}

$strings = array_chunk(array_unique($strings), 300);

foreach ($strings AS $stringChunk)
{
    //implode $stringChunk with ',' and insert into database
}
:) Now I have about 2.6 million possible combinations. That should last me.. forever.