我已经实现了计算数组反转的算法(它也合并了数组),但是为了使它更加整洁,我想对输出进行排序和计数。
Method * count_and_sort *返回数组[number_of_inversions,[sorted_array]]。 方法 inversions 和* merge_sort *应该分别返回number_of_inversions和[sorted_array],但我得到 NoMethodError
我错过了什么?
class Array
def inversions
count_and_sort[0]
end
def merge_sort
count_and_sort[1]
end
def merge_sort!
replace merge_sort
end
private
def count_and_sort
return [0, self] if self.size <= 1
left, right = partition.with_index{ |value, index| index < self.size / 2}
left = left.count_and_sort
right = right.count_and_sort
merged = merge(left[1], right[1])
[left[0] + right[0] + merged[0], merged[1]]
end
def merge(left, right)
inversions = 0
merged = []
until left.empty? || right.empty?
if left.first < right.first
merged << left.shift
else
merged << right.shift
inversions += left.size
end
end
merged += left += right
[inversions, merged]
end
end
p [*1..20].shuffle.inversions
我尝试用
替换 inversionsdef inversions
result = self.send(:count_and_sort)
result[0]
end
但结果是一样的。
PS欢迎任何其他批评和评论;)
答案 0 :(得分:2)
错误在count_and_sort
方法内,如错误消息所示:
... in 'count_and_sort': private method 'count_and_sort' called for ...
错误的行是:
left = left.count_and_sort
right = right.count_and_sort
Ruby中的私有方法无法使用显式接收器调用,必须在self
上隐式调用它们。因此,您可以使count_and_sort
方法受到保护,也可以使用send
和left
上的right
进行调用。在这种情况下,我会建议前者。