Search code examples
c++recursionmultimap

Find the length of a key, value chain in a multimap


I have a networking program that lets the user add 2 people to a multimap. The key is recruiter and the value is the person they add, the value can add another person so on and so forth. Here is an example

> add john mary
> add john tom
> add mary brad
> add tom Maria
> add mary Eli
> add brad Sofia

If I were to print john's chain, then I'd get the following.

> p john
john
..mary
....brad
......sofia
....eli
..tom
....maria

I need to find a way to count the length of the chain. In this case, length of john's chain is 6 and Mary has a length of 3.

This is how I print the chain

void print_subnet(std::multimap<std::string, std::string>networkMap, std::string id, size_t count=2)
{
    for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
    {
        if(itr ->first == id)
        {
            std::cout << std::string(count, '.') << itr -> second << std::endl;
            print_subnet(networkMap, itr->second, count+2);
        }

    }
}

I followed a similar logic to get the chain length.

  • for a given key, get the count.
  • set the value of the key as the new key
  • repeat until the end of map.

Here is my code.

 int count_size(std::multimap<std::string, std::string>networkMap, std::string id, int count)
    {
        for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
        {
            if(itr->first == id)
              {
                count += networkMap.count(id);
                count_size(networkMap, itr->second, count);
            }
        }
        return count;
    }

I get the answer 4, when it's supposed to be 6. I printed out the count value and this is what I got.

2 (2 from john)
4 (2 from mary)
5 (1 from brad)
6 (1 from tom)
4 ??
5 ??
4 ??

I'm pretty sure I'm missing something simple, but I've been at this for a while, I can't think straight.


Solution

  • This code returns 6:

    void count_size_recursive(std::multimap<std::string, std::string>networkMap, std::string id, int& count)
    {
      for(auto itr = networkMap.begin(); itr != networkMap.end(); ++itr)
      {
        if(itr->first == id)
        {
          ++count;
          count_size_recursive(networkMap, itr->second, count);
        }
      }
    }
    
    int count_size(std::multimap<std::string, std::string>networkMap, std::string id)
    {
      int count = 0;
      count_size_recursive(networkMap, id, count);
      return count;
    }