PHP Algorithm to Evenly Distribute Items into 3 Columns
This is the second time in my PHP career I've needed this so thought I'd commit it to a blog for easy access next time and save myself some brain MIPS. I want to evenly distribute items into three piles, making sure that no pile can have more than 1 extra item, and should a pile need 1 more than the other piles, then the item should go to the left-most first. This is better explained by way of a diagram. My pile of items is shown as letters of the alphabet.
Ok, the actual solution isn't particularly difficult, but it needed a little contemplation. Reproduced below we have the answer.
$count = count($rows);
$columns = 3;
$col1 = floor(($count + $columns - 1) / $columns);
$col2 = floor(($count + $columns - 2) / $columns);
$col3 = floor(($count + $columns - 3) / $columns);
Here we are saying that the count for each column is held in $col1, $col2 and $col3 respectively.