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

これはおそらく、グラフ理論の問題として最もよく解決されます。データを表す適切なグラフを作成する方法を理解し、そのグラフをたどって答えを得る必要があります。

于 2013-06-18T01:43:00.807 に答える
0

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 ...
}
于 2013-06-18T01:34:33.567 に答える