To follow up my original answer, the following code will generate all possible combinations of the boxes arranged in sets of 3 (brute-force approach):
class Combinations implements Iterator
{
protected $c = null;
protected $s = null;
protected $n = 0;
protected $k = 0;
protected $pos = 0;
function __construct($s, $k) {
if(is_array($s)) {
$this->s = array_values($s);
$this->n = count($this->s);
} else {
$this->s = (string) $s;
$this->n = strlen($this->s);
}
$this->k = $k;
$this->rewind();
}
function key() {
return $this->pos;
}
function current() {
$r = array();
for($i = 0; $i < $this->k; $i++)
$r[] = $this->s[$this->c[$i]];
return is_array($this->s) ? $r : implode('', $r);
}
function next() {
if($this->_next())
$this->pos++;
else
$this->pos = -1;
}
function rewind() {
$this->c = range(0, $this->k);
$this->pos = 0;
}
function valid() {
return $this->pos >= 0;
}
//
protected function _next() {
$i = $this->k - 1;
while ($i >= 0 && $this->c[$i] == $this->n - $this->k + $i)
$i--;
if($i < 0)
return false;
$this->c[$i]++;
while($i++ < $this->k - 1)
$this->c[$i] = $this->c[$i - 1] + 1;
return true;
}
}
$fruits = array(1, 2, 4, 5, 6, 8, 9, 11, 14);
foreach(new Combinations($fruits, 3) as $k => $v)
echo implode(',', $v), "<br />\n";
The output:
1,2,4
1,2,5
1,2,6
1,2,8
1,2,9
1,2,11
1,2,14
1,4,5
1,4,6
1,4,8
1,4,9
1,4,11
1,4,14
1,5,6
1,5,8
1,5,9
1,5,11
1,5,14
1,6,8
1,6,9
1,6,11
1,6,14
1,8,9
1,8,11
1,8,14
1,9,11
1,9,14
1,11,14
2,4,5
2,4,6
2,4,8
2,4,9
2,4,11
2,4,14
2,5,6
2,5,8
2,5,9
2,5,11
2,5,14
2,6,8
2,6,9
2,6,11
2,6,14
2,8,9
2,8,11
2,8,14
2,9,11
2,9,14
2,11,14
4,5,6
4,5,8
4,5,9
4,5,11
4,5,14
4,6,8
4,6,9
4,6,11
4,6,14
4,8,9
4,8,11
4,8,14
4,9,11
4,9,14
4,11,14
5,6,8
5,6,9
5,6,11
5,6,14
5,8,9
5,8,11
5,8,14
5,9,11
5,9,14
5,11,14
6,8,9
6,8,11
6,8,14
6,9,11
6,9,14
6,11,14
8,9,11
8,9,14
8,11,14
9,11,14
Now you just need to select 3 distinct sets (the sum of each one should be 19, 20 and 21).