gpt4 book ai didi

ruby - 创建类关系

转载 作者:数据小太阳 更新时间:2023-10-29 08:37:22 25 4
gpt4 key购买 nike

给定一个模块数组,返回描述模块之间规范化(最小)排序关系的数组的最佳方法是什么?数组的每个元素应该是具有父子关系的模块对的数组。每对中的子-父顺序很重要,但对之间的顺序无关紧要。归一化排序意味着任何可以从传递性派生的东西都应该从数组中排除。

例如,给定 [Object, Comparable, Float, Fixnum, Integer] ,答案是:

[
[Float, Object],
[Float, Comparable],
[Fixnum, Integer],
[Integer, Object],
[Integer, Comparable],
]

数组中的五对对应于这张哈斯图中的五条边: Hasse diagram

提示:Module#<=>other返回 -1 , 0 , 1如果存在顺序关系,并且nil如果没有顺序关系。

最佳答案

def ordering(mods)
a = mods.permutation(2)
.select { |m1,m2| (m1<=>m2) == -1 }
a.reject { |m1,m2|
mods.any? { |m| a.include?([m1,m]) && a.include?([m,m2]) } }
end

ordering([Object, Comparable, Float, Fixnum, Integer])
#=> [[Float, Object],
# [Float, Comparable],
# [Fixnum, Integer],
# [Integer, Object],
# [Integer, Comparable]]

mods = [Object, Comparable, Float, Fixnum, Integer, String, Array,
Hash, Enumerable, Enumerator, Module, Method, IO, File]
ordering(mods)
#=> [[Float, Object], [Float, Comparable],
# [Fixnum, Integer],
# [Integer, Object], [Integer, Comparable],
# [String, Object], [String, Comparable],
# [Array, Object], [Array, Enumerable],
# [Hash, Object], [Hash, Enumerable], [Hash, Object],
# [Hash, Enumerable],
# [Enumerator, Object], [Enumerator, Enumerable],
# [Module, Object],
# [Method, Object],
# [IO, Object], [IO, Enumerable],
# [File, IO]]

关于ruby - 创建类关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28425917/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com