php string permutation

2019-09-09 11:25发布

Let's say I have an array consisting of characters from these ranges "a-zA-Z0-9". What I want to do is get all possible combinations possible in a 4-letter range. Characters can be repeated in the string. I'm looking for a brute-force way to do it.

This is how I believe the iteration would be:

"aaaa" "aaab" "aaac" ... "9999"

2条回答
我命由我不由天
2楼-- · 2019-09-09 12:20

to random access you can use base_convert:

function getHash($i)
{
  //- allowed Letters
  $letters = 'aAbBcCdDeEfFgG';
  $len = strlen($letters);

  //- convert $i to base of $letters
  $i_in_base_of_letter = base_convert($i, 10, $len);

  //- replace letters
  return strtr($i_in_base_of_letter, '0123456789abcdefghijklmnopqrstuvwxyz', $letters);

}

or manuel if your base is larger then 36 (you have more then 36 Chars)

function getHash($i)
{
  //- allowed Letters
  $letters = 'aAbBcCdDeEfFgG';
  $letters_arr = str_split($letters, 1);

  $len = strlen($letters);

  $out ='';

  if ($i>0)
  {
    while ($i>0)
    {
      $r = $i % $len;
      $out = $letters_arr[$r] . $out;
      $i = floor ($i / $len);
    }
    return $out;
  }
  else
  {
    return $letters_arr[0];
  }
}

to iterate you can use:

for($i=0; $i<100; $i++)
{
  echo getHash($i) ."\n";
}

this way is not that fast as the brute force methode.

Regards Thomas

查看更多
放我归山
3楼-- · 2019-09-09 12:23

In brute-force fashion:

$chars = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
$cnt = count($chars);
$strings = array();
for ($first = 0; $first < $cnt; $first++) {
   for ($second = 0; $second < $cnt; $second++) {
       for ($third= 0; $third< $cnt; $third++) {
           for ($fourth= 0; $fourth < $cnt; $fourth++) {
              $strings[] = $chars[$first] . $chars[$second] . $chars[$third] . $chars[$fourth];
           }
       }
   }
}

You'll end up with a honkin' big array, so you might want to sprinkle some database operations into one of the loops, so $strings doesn't get too big and kill your script by hitting a memory limit.

查看更多
登录 后发表回答