function count_chairs($arr)
{
// how many elements in array
$i = count($arr);
echo $i;
// Creat an index to positions 0, 2, 4, ... $i
$index = range(1, $i, 2);
// Return the data at positions 0, 1, 2, ...
$out = array();
foreach($index as $key)
{
if(array_key_exists($key, $arr))
{
$out[] = $arr[$key];
}
}
return($out);
}
$arychairs= range(1,100);
while(count( $arychairs ) > 1 )
{
$arychairs = count_chairs($arychairs);
echo "<pre>";
print_r($arychairs);
echo "</pre>";
}
There is something not quite right with this algorithm I'm having trouble figuring what.
According to the current function the last chair is 64 but that is not the right surviving chair.
this is the output:
Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
[5] => 12
[6] => 14
[7] => 16
[8] => 18
[9] => 20
[10] => 22
[11] => 24
[12] => 26
[13] => 28
[14] => 30
[15] => 32
[16] => 34
[17] => 36
[18] => 38
[19] => 40
[20] => 42
[21] => 44
[22] => 46
[23] => 48
[24] => 50
[25] => 52
[26] => 54
[27] => 56
[28] => 58
[29] => 60
[30] => 62
[31] => 64
[32] => 66
[33] => 68
[34] => 70
[35] => 72
[36] => 74
[37] => 76
[38] => 78
[39] => 80
[40] => 82
[41] => 84
[42] => 86
[43] => 88
[44] => 90
[45] => 92
[46] => 94
[47] => 96
[48] => 98
[49] => 100
)
50
Array
(
[0] => 4
[1] => 8
[2] => 12
[3] => 16
[4] => 20
[5] => 24
[6] => 28
[7] => 32
[8] => 36
[9] => 40
[10] => 44
[11] => 48
[12] => 52
[13] => 56
[14] => 60
[15] => 64
[16] => 68
[17] => 72
[18] => 76
[19] => 80
[20] => 84
[21] => 88
[22] => 92
[23] => 96
[24] => 100
)
25
Array
(
[0] => 8
[1] => 16
[2] => 24
[3] => 32
[4] => 40
[5] => 48
[6] => 56
[7] => 64
[8] => 72
[9] => 80
[10] => 88
[11] => 96
)
12
Array
(
[0] => 16
[1] => 32
[2] => 48
[3] => 64
[4] => 80
[5] => 96
)
6
Array
(
[0] => 32
[1] => 64
[2] => 96
)
3
Array
(
[0] => 64
)
The first returned array is right, it removes 1,3,5,...99 and leaves chairs 2,4,6...100.
The second array is wrong. It should leave chairs 6,14,22,38,46,54,62,70,78,86 &94 instead of 4,8,12,16,20,24...100.
Maybe it is just not removing what was already removed? HOw do I unset the first set before starting on the second set in the foreach? I think that will solve it.
The problem again:
You are in a room with a circle of 100 chairs. The chairs are numbered sequentially from 1 to 100, the person in chair #1 will be asked to leave. The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave. This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left.
thanks again.