0

In my program, Density represents the count that indicates number of nodes connected to particular node. For example, if some node has density of 3, that indicates it is connected to 3 other nodes in the undirected graph. I want to decide the node that has highest density. Till now I am doing something like this:

    public Node LeaderIs(List<Node> list)
    {
        for (int k = 0; k < list.Count; k++)
        {
            var i = YelloWPages.GetNode(k, list);
            for (int l = 0; l < list.Count; l++)
            {
                var j = YelloWPages.GetNode(l, list);
                if (Node.GetDensity(i) > Node.GetDensity(j))
                {
                    Node Leadernode = i;
                }
            }
        }
    }

I have two questions:

  1. If this is correct? And if yes, from where should I return the Leadernode?
  2. If it is not correct, where I have went wrong and what implementation can be done to get Leadernode ?
John Saunders
  • 160,644
  • 26
  • 247
  • 397
LearningAsIGo
  • 1,240
  • 2
  • 11
  • 23

1 Answers1

0

To answer your questions:

1) No , this is not quite correct since you never return the value and you don't need the inner loop. Your not trying to sort the list, you just need the max value.

2) You need to define Leadernode at the top of your method, set it in the middle of your test condition and return it at the end of the method

public Node LeaderIs(List<Node> list)
{
    Node Leadernode = null;
    int LeadernodeDensity = 0;
    for (int k = 0; k < list.Count; k++)
    {
        var i = YelloWPages.GetNode(k, list);
        int iDensity = Node.GetDensity(i); 
        if ( iDensity > LeadernodeDensity)
        {
            Leadernode = i;
            LeadernodeDensity = iDensity;
        }

    }
    return Leadernode;
}

See the answers to a similar question here for better max value algorithms using C#.

LINQ: How to perform .Max() on a property of all objects in a collection and return the object with maximum value

Community
  • 1
  • 1
Mike Parkhill
  • 5,511
  • 1
  • 28
  • 38
  • It is giving me error at return statement saying "use of unassigned local variable". How can it be resolved? – LearningAsIGo Apr 27 '14 at 00:57
  • You need to default it to null (I've updated my answer). Presumably, you would always have a node with a density greater than zero, but better safe than sorry. It also means that whatever code is calling this should be checking for null. – Mike Parkhill Apr 27 '14 at 01:25
  • The above implementation did not work. However, marked as an answer because LINQ implementation in the provided link seems to be working fine. – LearningAsIGo Apr 29 '14 at 04:09