how to make a function recursive [message #174968] |
Wed, 27 July 2011 17:58 |
jr
Messages: 4 Registered: January 2011
Karma:
|
Junior Member |
|
|
I have this circle of chairs from 1-100. I want to subtract every
other chair starting from chair 1 recursively until I find the last
remaining chair.
I could do it in passes with the function below by returning $out.
I thought I could make the function recursive by adding the return
(count($arr[$key])==1?$out: count_chairs($arr)) instead of $out but I
don't know how to pass the first array in and then pass in the
difference of the $out and the new array on each pass?
Thanks,
?php
function count_chairs($arr)
{
// how many elements in array
$i = count($arr);
// 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)
{
$out[] = $arr[$key];
}
return $out;
}
//fill array
$arychairs= range(1,100);
$filtered = count_chairs($arychairs);
echo "<pre>";
print_r($filtered);
echo "</pre>";
?>
-------------------------------------------------
The remaining chairs from the first pass is all the even chairs.
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
)
|
|
|