使用for循环和ceil创建平衡组

时间:2019-01-05 23:24:29

标签: php

使用以下代码,我可以在一个循环中创建3个组-

$groupSize = ceil($number_students/3);
$j=1; 
for($i=1;$i<$number_students;$i++){
    if($i%$groupSize == 1){
        if($i!=0){
            echo '</fieldset>';
        }
        echo '<fieldset><legend>Group #'.$j.'</legend>';
        $j++;
    }
    echo '<div>Student #'.$i.'</div>';
}
echo '</fieldset>';

如果$number_students = 7的结果是

Group #1
    Student #1
    Student #2
    Student #3
Group #2
    Student #4
    Student #5
    Student #6
Group #3
    Student #7

我如何修改循环,以便平衡每个组,即。

Group #1
    Student #1
    Student #2
    Student #3
Group #2
    Student #4
    Student #5
Group #3
    Student #6
    Student #7

2 个答案:

答案 0 :(得分:2)

通过使用具有浮点值(fmod)的模,将为您提供此功能。 每次遇到小于1的余数时,我们都会创建一个新组。请注意,为了更适合模运算,我将$i的基数更改为0。

$numberStudents = 7;
$groupCount = 3;
$groupSize = $numberStudents/$groupCount;                // Will be 2.333..
$j=1;
for($i=0;$i<$numberStudents;$i++){
    if(fmod($i,$groupSize) < 1){
        if($i!=0){
            echo '</fieldset>';
        }
        echo '<fieldset><legend>Group #'.$j.'</legend>';
        $j++;
    }
    echo '<div>Student #'.($i+1).'</div>';
}
echo '</fieldset>';

其余部分应依次为:

> $i 0    remainder 0                (New Group 1)
> $i 1    remainder 1
> $i 2    remainder 2
> $i 3    remainder 0.66666666666667 (New Group 2)
> $i 4    remainder 1.66666666666667
> $i 5    remainder 0.33333333333333 (New Group 3)
> $i 6    remainder 1.33333333333333

在此示例中,有效地给小组中的3、2、2个学生提供了结果。 将数字更改为5个组中的17个学生也可以很好地工作,请注意,在这种情况下,生成组将是4,3,4,3,3,因此较大的组可能并不总是以第一个组结尾一个。

答案 1 :(得分:0)

使用this answer中的PHP Function to devide an array of N elements in N sub array,我可以在循环显示组之前先将它们分成平衡的组来解决。

function partition($list, $p) {
    $listlen = count($list);
    $partlen = floor($listlen / $p);
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for($px = 1; $px <= $p; $px ++) {
        $incr = ($px <= $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice($list, $mark, $incr);
        $mark += $incr;
    }
    return $partition;
} 

$number_students = 7;

$array = range(1, $number_students);
$number_of_split = 3;
$group = partition($array, $number_of_split);

foreach($group as $key => $students){
  echo '<fieldset><legend>Group #'.$key.'</legend>';
    foreach($students as $studentNum){
        echo '<div>Student #'.$studentNum.'</div>';
    }
echo '</fieldset>';
}