note 88330 added to function.array-key-exists
| From: | csaba at alum dot mit dot edu | Date: | Tue, 20 Jan 2009 13:13:15 +0000 |
| Subject: | note 88330 added to function.array-key-exists | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-149519@lists.php.net to get a copy of this message | ||
In some functions cacheing can be extremely useful, and this is especially true in recursive
functions, and all the more so in doubly recursive functions. One way to effect cacheing is to have
a static array in the function as shown below. This will typically be useful when a function has
one or two arguments and is heavily called. Example:
<?php
function nk($n, $k) {
// n choose k, ensuring integer math
if ($k > $n-$k) $k = $n - $k; // (n,k) = (n,n-k)
if ($k<=1) return ($k==1) ? $n : !$k; // (n,1) = n; (n,0)=1; (n,-#) = 0
static $aNK = array(); // caching section
if ($aNK[$n][$k]) return $aNK[$n][$k];// if answer already computed => done
// else compute answer, cache it, and return
return ($aNK[$n][$k] = nk($n-1, $k) + nk($n-1, $k-1)); }
$n = 20;
$k = 9;
$nk = nk($n,$k);
print "nk($n, $k) = $nk";
?>
For functions of two arguments, using a two dimensional array seems to be faster than combining
arguments a la "$n $k", and the form of testing shown above is also faster than
array_key_exists. However, to avoid the use of array_key_exists, special consideration must be
given to empty values (several prior notes cover this) - the example above works because no cached
value can be 0.
Csaba Gabor from Vienna
----
Server IP: 192.35.244.50
Probable Submitter: 80.108.23.194
----
Manual Page -- http://www.php.net/manual/en/function.array-key-exists.php
Edit -- https://master.php.net/note/edit/88330
Del: integrated -- https://master.php.net/note/delete/88330/integrated
Del: useless -- https://master.php.net/note/delete/88330/useless
Del: bad code -- https://master.php.net/note/delete/88330/bad+code
Del: spam -- https://master.php.net/note/delete/88330/spam
Del: non-english -- https://master.php.net/note/delete/88330/non-english
Del: in docs -- https://master.php.net/note/delete/88330/in+docs
Del: other reasons-- https://master.php.net/note/delete/88330
Reject -- https://master.php.net/note/reject/88330
Search -- https://master.php.net/manage/user-notes.php