0

我有一个点集合,我正在尝试编写一个将所有相关点分组的函数。

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

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}

有什么建议么?

更新:这是我的实现,以使其更清晰。这行得通,但我想知道这是否是正确的方法

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;


}

}

4

2 回答 2

0

转换int[] pointsDictionary<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 ...
}
于 2013-06-18T01:34:33.567 回答
0

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

于 2013-06-18T01:43:00.807 回答