Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condition in recursion - best practise

what's the best practise to break a loop? my ideas were:

Child Find(Parent parent, object criteria)
{
    Child child = null;

    foreach(Child wannabe in parent.Childs)
    {
        if (wannabe.Match(criteria))
        {
            child = wannabe;
        }
        else
        {
            child = Find(wannabe, criteria);
        }

        if (child != null) break;
    }

    return child;
}

or

Child Find(Parent parent, object criteria)
{
    Child child = null;
    var conditionator = from c in parent.Childs where child != null select c;

    foreach(Child wannabe in conditionator)
    {
        if (wannabe.Match(criteria))
        {
            child = wannabe;
        }
        else
        {
            child = Find(wannabe, criteria);
        }
    }

    return child;
}

or

Child Find(Parent parent, object criteria)
{
    Child child = null;
    var enumerator = parent.Childs.GetEnumerator();

    while(child != null && enumerator.MoveNext())
    {
        if (enumerator.Current.Match(criteria))
        {
            child = wannabe;
        }
        else
        {
            child = Find(wannabe, criteria);
        }
    }

    return child;
}

what do u think, any better ideas? i'm looking for the niciest solution :D

mo

like image 331
mo. Avatar asked Feb 15 '26 14:02

mo.


2 Answers

Linq may be more terse, but can be more difficult to understand!

    Child Find(Parent parent, object criteria)
    {
        return parent.Childs.Select(        // Loop through the children looking for those that match the following criteria
            c => c.Match(criteria)          // Does this child match the criteria?
                ? c                         // If so, just return this child
                : this.Find(c, criteria)    // If not, try to find it in this child's children
        ).FirstOrDefault();                 // We're only interested in the first child that matches the criteria or null if none found
    }
like image 191
Daniel Renshaw Avatar answered Feb 18 '26 04:02

Daniel Renshaw


There's no need for you to deal with the IEnumerator yourself, so option 3 is out.

Option 2 does not function. It continues regardless of finding a match, and if the last child is not a match and its children do not contain a match, then the result will be null even if there was a prior match.

Option 1 seems the cleanest, assuming you object to multiple return statements.

like image 30
Adam Robinson Avatar answered Feb 18 '26 02:02

Adam Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!