【发布时间】:2010-07-26 20:49:36
【问题描述】:
我想我只是看这个太久了。我有一些看起来像这样的数据:
@a = (
{ name => 'ethan', depth => 0 },
{ name => 'victoria', depth => 1 },
{ name => 'stephen', depth => 2 },
{ name => 'christopher', depth => 3 },
{ name => 'isabella', depth => 2 },
{ name => 'ethan', depth => 3 },
{ name => 'emma', depth => 0 },
{ name => 'michael', depth => 1 },
{ name => 'olivia', depth => 2 },
{ name => 'alexander', depth => 3 },
{ name => 'stephen', depth => 1 },
{ name => 'sophia', depth => 0 },
{ name => 'michael', depth => 1 },
{ name => 'ava', depth => 1 },
{ name => 'joshua', depth => 2 }
);
这是一个简单的“树”数据结构。每次'depth' = 0,那是一个新的'树'的开始。我想知道的是,每个名字出现在这些树中有多少棵?期望的结果是一个以名称为键、计数为值的散列。
其中的问题是,如果您仔细观察,第一棵树包含两个名称“ethan”。任何一棵树都可以有多个名字,但这只能算作 1,因为它们都出现在同一棵树中。但是,“michael”的计数为 2,因为他出现在两棵不同的树中。
我可以想到几种方法来做到这一点,但它们都涉及多个循环,并且看起来有些蛮力和不优雅。希望其他人可以提出更好的解决方案。
【问题讨论】:
-
选择这种结构来表示一棵树有什么特别的原因吗?我能想到一些更直观的格式。 :)
-
它主要是一种输出格式——它不需要太多的“树”功能,只需要每个条目缩进多少。我没有预见到一旦我发布了这个工具,我的同事会要求更多的功能,或者我一开始会把它表示为一棵树。
标签: perl arrays hash tree intersection