I want to write a function that return random unique pair numbers every time call it from a range until resetting it. Something like this:
function randomUniquePairs($ranges, $reset = false){
if ($reset === false){
// some code for reseting
}
/*
some code for creating random unique pair numbers
*/
return $result;
}
randomUniquePairs(range(1,10), range(1,20));
/*
this function returns for example:
array(2,9)
*/
randomUniquePairs(range(1,10), range(1,20));
/*
this function returns for example:
array(5,19)
*/
randomUniquePairs(range(1,10), range(1,20));
/*
this function returns for example:
array(5,9)
*/
//this function returns random unique pairs until we pass reset paramer true
I tried two approaches:
Approach 1
My first attempt was to make an array of all of possible pairs then select from them randomly, but it is very inefficient, because if ranges are so wide, it consumes a lot of memory.
the code:
class a {
private $asqar;
function __construct() ($range) {
// cycle for ranges
foreach ($range[0] as $v1) {
foreach ($range[1] as $v2) {
$asqar[] = array(
$v1,
$v2,
);
}
}
}
function randomUniquePairs($reset = false){
if ($reset === true){
$this->asgar = array();
}
$rndKey = array_rand($this->asgar);
$result = $this->asqar[$rndkey];
unset($this->asqar[$rndkey]);
return $result;
}
}
$c = new a(range(1,10), range(1,20));
$c->randomUniquePairs();
Approach 2
My second attempt was to write a function that produce a pair from these ranges, then store it in a variable, every time that function calls after producing a pair , it checks if this pair produced before call function recursively, it continues until it produce a unique pair.
Here's the code:
class a{
private $__uniqueVariables = array();
public function randomUniquePairs($range, $reset = false) {
if ($reset === true){
$this->__uniqueVariables = array();
}
// cycle for each value
foreach ($range as $value) {
// shuffle
shuffle($value);
// selected id
$selectedId[] = $value[0];
}
// check for selected variable
if (in_array($rndUnqNum, $this->__uniqueVariables)) {
// return for try again
return $this->uniqueVariable($range);
}
// added to current unique variables
$this->__uniqueVariables[] = $rndUnqNum;
// return
return $rndUnqNum;
}
}
but this second approach has an issue that sometimes throw Fatal error: Maximum function nesting level of '100' reached
.
I'm looking for a better approach to my algorithm.
do
/while
loop instead of calling itself recursively.function nesting level
limit, while ado/while
can just keep going until it finds a result.