【问题标题】:shuffle Numbers without triple Repeat in row随机排列没有三次重复的数字
【发布时间】:2020-03-06 05:50:08
【问题描述】:

用数字打乱数组而不连续重复三次的最快方法是什么

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

1,1,1,2,2,2,...不好????????

1,1,2,2,1,2,...好????????

1,2,1,2,1,2,...好????????

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

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

【问题讨论】:

  • 什么是 tribble?
  • 我不确定,但可能你想要这样:-3v4l.org/BaU8o(数据不会以三个为一组重复)
  • 不是真的
  • $max= 最多连续重复 2 次。我发现这个函数不是那么容易,因为你可以在数组的末尾有很多未使用的数字。这个算法比我之前想的更难开发
  • 这很好用 3v4l.org/QCeJ2

标签: php random repeat triples


【解决方案1】:

这是带有“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));

【讨论】:

  • 能否请您测试一下我最终修改的代码?让我知道它对你有用吗?
猜你喜欢
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2022-06-17
  • 2012-12-11
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多