2014-03-04 36 views
2

我正在解決將一些元素按照他們的友誼分組到不同的組中的問題。C#通過他們的友誼重新組合一些元素到不同的循環中

例如,

輸入:

R1: R2, R6, R8, R10 // all elements in one group are friends 
R6: R1, R7, R8, R12 
R8: R2, R5, R6, R10 
R4: R11, R15, R16, R13 // **UPDATE** this is a group that do not have overlap with all other groups 

對於R1,R1的所有的朋友的朋友也需要被分爲一組等誰R1的朋友。

預期輸出:

R1: R2, R6, R8, R10 , R7, R5, R12 
R4: R11, R15, R16, R13 // **UPDATE** 

的輸出可以是兩個或更多個groups.It取決於輸入。現在

,該數據被存儲在C#字典>在Visual Studio 2012

我發現,有可能在分組處理週期。

例,R1 ---> R6 ---> R8 - > R6

請你幫我看看如何解決這個問題的週期。

任何幫助,將不勝感激。

感謝

+2

小很難理解你的要求。這些「組」存儲在哪裏?你如何創建詞典?你在尋找什麼樣的輸出? –

+0

一些演示代碼會很棒。另外,請爲您的示例提供期望的結果。如果您只想消除重複項,請查看[HashSet ](http://msdn.microsoft.com/zh-cn/library/vstudio/bb359438(v = vs.100).aspx) –

+0

向我們展示示例輸入,預期產出和實際產出。 – Dialecticus

回答

1

演示代碼如下所示:

private static Dictionary<string, List<string>> ProcessData(Dictionary<string, List<string>> data) 
    { 
     var processedData = new Dictionary<string, List<string>>(); 
     var masterList = new List<string>(); 
     foreach (var value in data.Keys) 
     { 
      if (!masterList.Contains(value)) 
      { 
       var friendList = FindFriends(data, value); 
       masterList.AddRange(friendList); 
       processedData.Add(value, friendList); 
      } 
     } 
     return processedData; 
    } 

    private static List<string> FindFriends(Dictionary<string, List<string>> data,string source) 
    { 
     var friendMasterList = new List<string>(); 
     var friendQueue = new Queue<string>(); 
     if (data.ContainsKey(source)) 
     { 
      foreach (var value in data[source]) 
      { 
       friendQueue.Enqueue(value); 
      } 
      while (friendQueue.Count > 0) 
      { 
       var value = friendQueue.Dequeue(); 
       if (!friendMasterList.Contains(value)) 
        friendMasterList.Add(value); 

       if (data.ContainsKey(value)) 
       { 
        foreach (var value2 in data[value]) 
        { 
         if (!friendMasterList.Contains(value2)) 
          friendQueue.Enqueue(value2); 
        } 
       } 
      } 
     } 
     if (friendMasterList.Contains(source)) 
      friendMasterList.Remove(source); 
     return friendMasterList; 
    }