发布于 5年前

php 以指定步长走完所有数

比如,有100个任务,想分给每个组4个非连续任务,25个组的情况下,希望每个任务都被分配一次。

代码:

<?php

$n=100;
$taskCount=7;

$step=getStep($n,$taskCount);
list($data,$spreadData) = getData($n,$step);

echo "步长为{$step}";
echo "\n";
echo "每一次循环得到的数据";
echo json_encode($data);
echo "\n";
echo "最后展开数据,可以依次截取七个";
echo json_encode($spreadData);
echo "\n";

function getStep($n,$taskCount){
    $a= (int)($n/$taskCount);
    while (true){
        if(huZhi($n,$a)){
            return $a;
            break;
        }

        $a--;
    }
}

/**
 * 两个数是否是互质
 * @param $a
 * @param $b
 * @return bool
 */
function huZhi($a,$b){
    if($a<$b){
        list($a,$b)=[$b,$a];
    }
    while($a%$b) {
        list($a,$b)=[$b,$a%$b];
    }
    return $b==1?true:false;
}

function getData($n,$step){
    $a=[];
    $b=[];
    $c=[];
    $i=0;
    do{
        $i+=$step;
        if($i>$n){
            $i=$i-$n;
            $a[]=$b;
            $b=[];
        }
        $b[]=$i;
        if($i==$n){
            $a[]=$b;
        }
        $c[]=$i;

    }while($i!=$n);
    return [$a,$c];
}

输出:

步长为13,每一次循环得到的数据

[[13,26,39,52,65,78,91],[4,17,30,43,56,69,82,95],[8,21,34,47,60,73,86,99],[12,25,38,51,64,77,90],[3,16,29,42,55,68,81,94],[7,20,33,46,59,72,85,98],[11,24,37,50,63,76,89],[2,15,28,41,54,67,80,93],[6,19,32,45,58,71,84,97],[10,23,36,49,62,75,88],[1,14,27,40,53,66,79,92],[5,18,31,44,57,70,83,96],[9,22,35,48,61,74,87,100]]

最后展开数据,可以依次截取七个

[13,26,39,52,65,78,91,4,17,30,43,56,69,82,95,8,21,34,47,60,73,86,99,12,25,38,51,64,77,90,3,16,29,42,55,68,81,94,7,20,33,46,59,72,85,98,11,24,37,50,63,76,89,2,15,28,41,54,67,80,93,6,19,32,45,58,71,84,97,10,23,36,49,62,75,88,1,14,27,40,53,66,79,92,5,18,31,44,57,70,83,96,9,22,35,48,61,74,87,100]
©2020 edoou.com   京ICP备16001874号-3