Search code examples
phprandomrepeattriples

shuffle Numbers without triple Repeat in row


What is the fastest way to shuffle an array with numbers without repeating trible times in a row

shuffleX(array(1,2,1,2,1,2,1,2,1,2,1,2,1),2)

1,1,1,2,2,2,... Bad 👎🏼

1,1,2,2,1,2,... Good 👍🏼

1,2,1,2,1,2,... Good 👍🏼

function shuffleX($arr, $max=2){

 ...
} 
$arr=array(1,2,1,1,2,2);
shuffleX($arr,2);

Solution

  • Here's my dirty Solution with an "while Check" https://3v4l.org/bFjZ5

    function shuffleX($arr, $max=3){
        $raw=$arr;
        $x=0;
        $s=md5('random_string');
        while(1){$x++;
            shuffle($arr);
                //Build string out of Arr for repeating variables to check
                $f2=join($s,$arr);
                $break=true;
    
                foreach($raw as $k=>$v){
                    //Check for repeating variables each Value (forward and Backward)
                    $f=str_repeat($v.$s,$max);
                    $fa=str_repeat($s.$v.'',$max);  
    
                    if(preg_match('#'.$f.'#',$f2) OR preg_match('#'.$fa.'#',$f2)){
                        $break=false;
                    }
    
            }
            if($break===true){return $arr;}
            if($x>(count($arr)*1000)){// if nothing found after x Times break or give an empty array
                return array('unpossible');
            }
        }
    
    }
    $arr=array(1,2,1,1,2,2,1,2,1,2,1);
    print_r(shuffleX($arr,3));