You are here: Re: Detecting Recursion « PHP Programming Language « IT news, forums, messages
Re: Detecting Recursion

Posted by Henk Verhoeven on 10/18/05 22:15

Hi Thomas,

Generally, for recursion detection you use a "Set". You use a either
breadth first search or a depth first search algorithm to go through the
graph of data structures, collection and/or objects and put every node
into the Set (google for these algorithms, or for backtracking
algorithm). Before every next step you also check if the next node is
already in the Set. The Set can answer this question very fast becuase
it uses Hashing. If it is in the set, skip it.

Your problem: php has no Set. But you can use an associative array and
add unique keys for each node, with some not-null value as value.
Something like this:
$visitedKeys[getUniqueKey($node)] = true;
Now you can check wheather the node was already visited by:
isSet($visitedKeys[getUniqueKey($node)])
I bet associative arrays use hasing, just like Sets (lookup is so fast).
Of course you do have to program the getUniqueKey function to work with
your actual data ;-)

Greetings,

Henk Verhoeven,
www.phpPeanuts.org

Thomas Mlynarczyk wrote:

> Hi,
>
> Say I have an array containing a reference to itself:
> $myArray = array();
> $myArray['self'] =& $myArray;
> How can I, looping iteratively through the array, detect the fact that
> $myArray['self'] will "take" me to where I have already been? The print_r()
> and var_dump() functions print *RECURSION* in such a case (though only after
> the "second round"). Setting a flag seems to be the only solution, but I
> don't want to modify the array in question - I want to produce a visual
> representation of its contents like var_dump(), but formatted to my taste. I
> had considered parsing the output of var_dump(), but first, that format
> might change in a future version of PHP and second, an array key might be a
> string resembling part of the output (like $myArray['["myArray"]=>']), which
> seems to be difficult to detect by the parsing code.
>
> Is there another way of doing this?
>
> Greetings,
> Thomas
>
>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация