Skip to content

Instantly share code, notes, and snippets.

@ArrayIterator
Last active December 28, 2022 18:34
Show Gist options
  • Save ArrayIterator/12f3e5e519ea2e22df2c9e7fa8fdb613 to your computer and use it in GitHub Desktop.
Save ArrayIterator/12f3e5e519ea2e22df2c9e7fa8fdb613 to your computer and use it in GitHub Desktop.
Random Character Permutation
<?php
/**
* Create possible random array permutation by characters
*/
function random_array_permutations($array_or_string, int $length, int $max = 10, array $must_be_not_in = []) : array
{
if (!is_array($array_or_string)) {
$array_or_string = str_split((string) $array_or_string);
}
$count = count($array_or_string);
if ($count === 0) {
return [];
}
// shuffling to random
shuffle($array_or_string);
// make it unique & no equal value
$array_or_string = array_unique($array_or_string);
// flipping value as key
$must_be_not_in = array_flip($must_be_not_in);
$data = [];
$possible = pow($max, $length);
while (count($data) < $max && $possible > 1) {
$possible--;
$current = '';
$e = 0;
while (strlen($current) < $length) {
// shuffling to random
shuffle($array_or_string);
if (!isset($array_or_string[$e])) {
$e = 0;
continue;
}
$current .= $array_or_string[$e++];
}
// coninue if contains
if (isset($must_be_not_in[$current])) {
continue;
}
// append as key
$data[$current] = 0;
}
return array_keys($data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment