在给定列表中找到最小的一对

时间:2018-11-01 15:57:58

标签: c#

让我们有一个成对的朋友int数组[{0,1},{1,2},{4,5}]的列表 我们如何找到与其他人成对的朋友。朋友列表将是(0,1,2)和(4,5)并以c#打印。 如果该数字存在于一对int数组中,则将其添加并以C#打印 例如;列表中有[{0,1},{1,2},{4,5}] 那么可能的打印将是(0,1,2)和(4,5)

让0,1是朋友,1,2是朋友,和4,5是朋友,然后0,1,2是朋友,4,5是朋友 >

1 个答案:

答案 0 :(得分:1)

此功能可满足您的需求吗?

List<int[]> pairsOfFriends = new List<int[]>
{
    new int[] {0, 1},
    new int[] {1, 2},
    new int[] {4, 5},
};
Dictionary<int, List<int>> friendsLists = new Dictionary<int, List<int>>();
pairsOfFriends.ForEach(pairOfFriends =>
{
    int friendA = pairOfFriends[0];
    int friendB = pairOfFriends[1];
    //if friendA has a friends list, then friendA wants to share his friends list with friendB!
    if (friendsLists.ContainsKey(friendA))
    {
        var friendsListA = friendsLists[friendA];
        //if friendB has a friend list, they also want to share all of their friends with friendA.
        if (friendsLists.ContainsKey(friendB))
        {
            //friendA copies all of friendB's friends into his own friends list
            friendsListA.AddRange(friendsLists[friendB]);
            //friendB and friendA then share friendA's friends list so that they share the same friends!
            friendsLists[friendB].ForEach(friendBsFriend =>
            {
                friendsLists.Remove(friendBsFriend);
                friendsLists.Add(friendBsFriend,friendsListA);
            });
        }
        else
        {
            //if friendB doesn't have any friends, then friendA shares all of his friends with friendB and then adds friendB to his own friends list
            friendsLists.Add(friendB, friendsListA);
            friendsListA.Add(friendB);
        }
        //if friendB has a friends list, and friendA doesnt then friendB adds friendA to his friends list and then shares his friends list with friendA.
    }
    else if (friendsLists.ContainsKey(friendB))
    {
        var friendsListB = friendsLists[friendB];
        friendsLists.Add(friendA, friendsListB);
        friendsListB.Add(friendA);
    }
    //if neither friendB or friendA have a friends list then friend a makes a new friends list, adds himself and friendB to it and then shares the friends list with friend B
    else
    {
        friendsLists.Add(friendA, new List<int> {friendA, friendB});
        friendsLists.Add(friendB, friendsLists[friendA]);
    }
});
friendsLists.Values.Distinct().ToList().ForEach(f =>
{
    Console.Write("("+string.Join(", ", f)+") ");
});