【问题标题】:Which data structure to use to implement family tree in ruby?在 ruby​​ 中使用哪种数据结构来实现家谱?
【发布时间】:2019-10-09 19:54:09
【问题描述】:

我正在尝试在 ruby​​ 中创建一个简单的家谱,我可以在其中通过母节点添加子节点。此外,当我将名称和关系作为输入时,我应该能够将输出作为与给定人名相关的人名。 例如,我应该能够执行以下操作 add_child('Tina', 'bob') // which will add bob as a child node to Tina get_relation(bob, maternal_uncles) // which should output all the siblings of Tina in this case.

哪种数据结构最适合实现这一点以及如何在 ruby​​ 中实现它?在我的研究中,我发现图表是一种很好的方法,我从 2 天以来一直在研究它的实施,但找不到任何解决方案。

我尝试了以下库

RubyTree https://github.com/evolve75/RubyTree - 这帮助我获得了父母,兄弟姐妹,祖父母的关系,但我想不出我怎么能用它来获得像父亲的兄弟(舅舅),妻子的姐妹(嫂子)这样的关系等等

weighted graph https://github.com/msayson/weighted_graph - 我用 0 代表配偶,用 1 代表孩子。我不能从这里去任何地方。我对如何获得特定人的父母和孩子感到困惑。

我对@9​​87654329@ 和rgl gem 进行了一些探索,但我无法将它们应用到我的应用程序中。

请帮忙。提前致谢!

【问题讨论】:

  • 使用Struct有什么问题?
  • 这是一个有趣的问题,但如果您将一个示例与一系列您希望回答的与示例相关的问题一起包含在内,它会大大改进。回想起来,我认为这样的例子是必不可少的。
  • add_child('Tina', 'bob') 有两个 Tina 时会发生什么?还是这种情况不会出现?
  • 如果你在做朴素的树而不是任何结构都可以做,但在现实世界中事情变得如此复杂,你需要一个循环图结构。

标签: ruby data-structures graph tree


【解决方案1】:

我可以想出一种使用RubyTree 本身来获得最小关系的方法。 RubyTree 有内置的方法,如父、兄弟、子等,我们也可以将内容传递给节点。 所以我用这些来得到我想要的。例如,为了创建配偶,我为根节点创建了一个子节点,并在内容中传递了一个像 {relation: spouse} 这样的哈希值。通过这种方式,我可以通过在这个哈希上设置条件来应用逻辑并获得我想要的关系

示例:

tina = Tree::TreeNode.new('Tina', {gender: 'female', relation: 'root'})
mike = tina << Tree::TreeNode.new('Mike', {gender: 'male', relation: 'spouse'}) 
sofi = tina << Tree::TreeNode.new('sofi', {gender: 'female', relation: 'child'})
...... #add all children and their children like this

puts "--------siblings of sofi--------"
siblings_of_sofi.each do |sib|
    if sib.content[:relation] == 'child'
        puts sib.name
    end
end

# assume tina has 4 sons and one of them is bob and alice is daughter of bob. 
puts "--------alice paternal uncles--------"
puts alice.parent.name
puts alice.parent.content
if alice.parent.content[:relation] == 'spouse'
    father = alice.parent.parent #as per the question child should be added through mother only, therefore alice is added as a child to bob's wife and bob's wife is added as a child to bob as {relation: spouse}
    uncles = father.siblings
    uncles.each do |uncle|
        puts uncle.name if uncle.content[:gender] == 'male' && uncle.content[:relation] == 'child'
    end

end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 2012-01-19
    • 2013-06-03
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    相关资源
    最近更新 更多