распределить номер без остатка

Я хочу распределить предмет по конкретным частям, не разрезая лишний кусок,
пример:

$persons = 7;
$rooms = 2;

for($i = 0; $i < $rooms; $i++)
{
//distribute the persons per room
}

//the endpoint should be
$the_room[0] = 4 //instead of 3.5
$the_room[1] = 3 //instead of 3.5

1

Решение

Как насчет подхода, который сначала равномерно распределяет части, а затем рандомизирует остаток?

$persons = 7;
$rooms = 2;
$the_room = array();

for($i = 0; $i < $rooms; $i++)
{
$the_room[$i] = floor($persons / $rooms);
}

// Random Distribution
while( $persons - array_sum($the_room) > 0)
{
$the_room[array_rand($the_room)]++;
}

// Sequential Distribution
// $index = 0;
// while( $persons - array_sum($the_room) > 0)
// {
//   $the_room[$index++]++;
// }

print_r($the_room);
2

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector