【发布时间】:2019-02-25 06:43:32
【问题描述】:
我有一本字典,其中包含一些数字键。每个键都有一组值,其中包含“嵌套”在该特定键中的数字(此数据已从数据库中提取)。
一些例子:
825 里面有 838,838 里面有 2941,2941 里面有 556。所以有 4 个嵌套级别。
825 里面有 27 个,这只是一个嵌套级别。
23 嵌套在 838 内(2 个嵌套级别),但 23 内有 66 个嵌套级别。
示例结构:
dictionary {
825 : [838, 27],
838 : [2941, 23],
2941 : [556, 612],
23 : [66]
}
我已经编写了一些代码,可以将数字嵌套在其他数字中,因为其中一项要求是了解嵌套的“深度”。
// example: call function with key: 825
public int getDepth(int number, Dictionary<int, List<int>> nestedNumbers, int depth)
{
// 825 is in nestedNumbers
if (nestedNumbers.Keys.Contains(number))
{
// foreach number in 825 [838, 27]
foreach (var currentNumber in nestedNumbers[number])
{
// depth is now level 2
depth++;
// call the function again but with 838, which will now get nested groups in 838 [2941, 23]
return getDepth(currentNumber, nestedNumbers, depth);
}
}
return depth;
}
我需要制作一个包含所有嵌套级别的列表(或数组列表),如下所示:
lvl1 lvl2 lvl3 lvl4
[[825, 838, 2941, 556],
[825, 27],
[825, 838, 23, 66],
[825, 838, 2941, 612]] <-- e.g. 612 is in 2941, 2941 is in 838, 838 is in 825
但是根据我已经编写的函数,我不确定如何去做。有谁知道我该如何实现这一目标?
【问题讨论】:
-
有错字吗?您的函数名为
getDepth(),但您在方法中调用GetDepth。这是不同的方法还是错字? -
您的
depth计算不准确。不要在循环内部增加——这会增加列表大小的深度。致电getDepth(currentGroup, nestedNumbers, depth + 1);。此外,在可能有多个路由到叶子的情况下,取这些getDepth调用中的最大值。 -
抱歉@maccettura 它是递归的,我忘了在 getDepth 上添加返回
-
啊,我明白你的意思了,它总是会落后一个深度级别
-
你的权利我的输出不是很清楚。我已经更新了它。我认为现在更清楚我想要实现的目标
标签: c# arrays dictionary tree nested