N
N
NikoB2011-06-16 23:33:06
PHP
NikoB, 2011-06-16 23:33:06

Iterating over possible values ​​in PHP?

Tell me a ready-made class / function or a way to generate all possible solutions with the alphabet A and the string length N
Ie . if $A='01'; and $N=3; it will be
000
001
010
011
100
101
110
111

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Dzuba, 2011-06-16
@NikoB

The method is called recursion. I threw an example on my knee:

$alphabet = 'abcd';
$length = 5;
$words = array();

function makeword($prefix)
{
  global $alphabet, $length, $words;
  if (strlen($prefix) == $length)
  {
    $words[] = $prefix;
    return;
  }
  for ($i = 0; $i < strlen($alphabet); $i++)
    makeword($prefix . $alphabet{$i});
}

makeword('');

// Все слова - в массиве $words
echo count($words);

S
Stanislav Agarkov, 2011-06-17
@stas_agarkov

they write this in the first year ... :(

Y
yaksa, 2011-06-16
@yaksa

The first thing that comes to mind is to look for brute scripts.

@
@message, 2011-06-17
_

As Alice said, brute force is suitable here, I also immediately thought about it ... Here I did it for your needs.

<?php

$text_lenght = 3;
$charset = '01';
$charset_length = strlen($charset);

function recurse($width, $position, $base_string)
{
    global $text_lenght, $charset, $charset_length;
     
    for ($i = 0; $i < $charset_length; ++$i) {
        if ($position  < $width - 1) {
            recurse($width, $position + 1, $base_string . $charset[$i]);
        }
    if (strlen($base_string . $charset[$i]) == $text_lenght) {
      echo $base_string . $charset[$i].'
';
    }		

    }
}

recurse($text_lenght, 0, '');
?>

I hope this is what you need

K
Kindman, 2011-06-23
@Kindman

If the alphabet is not more than 36 characters, then you can do this:

<?php
function brut36($A="0123456789", $N=1)
    {
    $base="0123456789abcdefghijklmnopqrstuvwxyz";
    $b=strlen($A);
    $count=pow($b, $N);
    for ($i=0;$i<$count;$i++)
      echo strtr(str_pad(base_convert($i, 10, $b), $N, "0",
        STR_PAD_LEFT), $base, $A),"\r\n";
    }

brut36("01", 3);
at the output we get:
000
001
010
011
100
101
110
111

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question