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,5C# 找到给定列表中的最小对,c#,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是朋友这能满足您的需要吗 List<int[]> pairsOfFriends = new Lis
让0,1是朋友,1,2是朋友,4,5是朋友,那么0,1,2是朋友,4,5是朋友这能满足您的需要吗
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)+") ");
});
如果您向我们展示您已经尝试过的内容,您会得到更好的响应。发布的值没有任何意义。我在函数中传递了数组列表,如:new int[3,2]{{0,1},{1,2},{3,4};试着找到配对这是完全相同的例子…啊,我想这个问题是关于如何找到循环。这里{0,1}和{1,2}组合形成{0,1,2}。