0

I am looking for an algorithm to generate an array of all possible 5 digit combinations of numbers in range 2-9 while having no repeating digits in combinations. For example: 23456 37895 62784 96742 83467 ...

What i don't want to see is for example: 22456 34463 44444 78772 ...

I have got code, which generates all possible combinations, but having repeating numbers in combinations. So maybe that array could be filtered instead having only combinations which contain unique digits.

function sampling($chars, $size, $combinations = array()) {
    $charsArray = str_split($chars);
    # if it's the first iteration, the first set 
    # of combinations is the same as the set of characters
    if (empty($combinations)) {
        $combinations = $charsArray;
    }

    # we're done if we're at size 1
    if ($size == 1) {
        return $combinations;
    }

    # initialise array to put new values in
    $new_combinations = array();

    # loop through existing combinations and character set to create strings
    foreach ($combinations as $combination) {
        foreach ($charsArray as $char) {
            $new_combinations[] = $combination . $char;
        }
    }
    # call same function again for the next iteration
    return sampling($chars, $size - 1, $new_combinations);

}

// example

$output = sampling("23456789", 5);
print "<pre>";print_r($output);
Taavi
  • 101
  • 2
  • `var_dump(count($output) === count(array_unique($output)));` gives me true. – nice_dev May 15 '21 at 13:46
  • I don't really get what numbers you're trying to generate. You say "in range 2-9" but show an example with "12345" (starting with a "1") which is not in that range? – M. Eriksson May 15 '21 at 13:59
  • see if this helps you - https://stackoverflow.com/questions/17778723/generating-random-numbers-without-repeats#:~:text=php%20function%20randomGen(%24min%2C,generates%2020%20unique%20random%20numbers%20%3F%3E – Dr Manish Lataa-Manohar Joshi May 15 '21 at 13:59
  • What i need is all possible combinations which only consist of unique digits or perhaps the array created by the code, which i provided, can be filtered. I have also edited the question. – Taavi May 15 '21 at 16:01

1 Answers1

0
<?php

$var = [];
for ($i = 20000; $i <= 99999; $i++) {
    $pass = true;
    if(is_numeric(strpos((string) $i, "0")) || is_numeric(strpos((string) $i, "1"))) {
        $pass = false;
    }
    if($pass) {
        $var[] = $i;
    }
}

foreach($var as $v) {
    echo "$v \n";
}

php script.php | grep 0

php script.php | grep 1

If you have repeating numbers you can use array_unique

But with the code above, you are sure not to omit or repeat anything

Alexis Gatuingt
  • 490
  • 6
  • 20