我有一系列积分,我正在尝试编写一个对所有相关点进行分组的函数。
例如,在这种情况下相关意味着项目包含另一个:
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;
}
}
答案 0 :(得分:0)
将int[] points
转换为Dictionary<int, string[]> pointTokens
e.g。
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 ...
}
答案 1 :(得分:0)
这可能最好解决为图论问题。您需要弄清楚如何创建适当的图表来表示您的数据,然后遍历它以获得答案。