c#集合组相关元素

本文关键字:元素 集合 | 更新日期: 2023-09-27 18:18:59

我有一个点的集合,我试图写一个函数组所有相关的点。

例如,在这种情况下,相关意味着一个项目包含另一个:

int[] points = {2, 3, 4, 5, 6, 7, 2, 13, 14, 15, 32, 10, 237, 22, 46, 97}
getDirectRelatives(2) = {2, 2, 32, 237, 22}

用于返回所有直接相关的元素。但我想把间接相关的因素归类。因为3和7与2有间接关系,所以我也想要它们所有的直接关系:

getAllRelatives(2) = {2, 2, 32, 237, 22, 3, 13, 32, 7, 97}

有什么建议吗?

Update:这是我的实现,使它更清楚。这是有效的,但我想知道这是否是正确的方法

public void getAllRelatives()
{
int groupIndex = 1;
List<int> groupCollection = new List<int>();
bool flag = false;
int[] marked = null;
string currentOuter = null;
string currentInner = null;
List<int> current = new List<int>();
int[] points = {2, 4, 5, 6, 7, 2, 13, 14, 15, 32, 10, 237, 22, 46, 97};
//marked contains integers which identify which group an element belongs to
for (x = 0; x <= marked.Count - 1; x++) {
    marked(x) = 0;
}
//Two loops.  The first iterates over the target point, the second iterates over each sub point
//Once both loops are complete, groupCollection should contain the indexes for
//all related integers
//outerloop
for (i = 0; i <= points.Count - 1; i++) {
    current.Clear();
    currentOuter = points(i).ToString;
    current.Add(i); //used to hold matches for current loop
    //inner loop, targetpoint + 1 to end
    for (x = i + 1; x <= points.Count - 1; x++) {
        currentInner = points(x).ToString;
        if (currentInner.Contains(currentOuter)) {
            current.Add(x);
        }
    }
    //if this is the first iteration, flag as true, forces current items to marked
    if (marked(0) == 0) {
        flag = true;
    }
    //check if any current points are marked and flag if any of the elements are already in a group, add each found group to group collection
    for (x = 0; x <= current.Count - 1; x++) {
        if (!(marked(current(x)) == 0)) {
            flag = true;
            groupCollection.Add(marked(current(x)));
        }
    }
    if (flag == true) {
        groupCollection.Add(groupIndex); //all relatives end up here
    }
    for (x = 0; x <= current.Count - 1; x++) {
        marked(current(x)) = groupIndex;
    }
    groupIndex += 1;
    flag = false;

}

}

c#集合组相关元素

int[] points转换为Dictionary<int, string[]> pointTokens

pointTokens.Add(237, new string[]{"2", "3", "7"})

然后使用pointTokens来查找关系(无论多么任意)

foreach(int point in pointTokens.Keys)
{
  string[] tokens = pointTokens[point]
  if(someInt.Equals(point))
  {
    // do something
  }
  if(tokens.Contains(someInt.ToString())
  {
     // do something
  }
  // etc ...
}

这可能是最好的解决图论问题。您需要弄清楚如何创建一个合适的图形来表示您的数据,然后遍历它以获得您的答案。