ruby - 二进制字母排序 ruby

标签 ruby algorithm sorting binary

我尝试编写自己的字母表搜索 Chris Pine tutorial chapter 7 ,我想实现一个二进制方法。字符串输入没有有效性,所以我不知道整数与字符串混合会发生什么,但我的想法是仅对字符串列表执行此操作。

#get list of strings
puts "type words to make a list. type 'exit' to leave program."
x = ()
list = []
while x.to_s.upcase != 'EXIT'
    x = gets.chomp
    list.push(x)
end 
list.pop

#binary method

nano = list.length
half= list.each_slice(nano/2).to_a
left = half[0]
right = half[1]

nanol=left.length
nanor=right.length

#initialize results array

A = []

for i in 0..nano-1
    smallest_left = left.min
    smallest_right = right.min

        #no difference with this commented out or not
    #if nanol==0
    #    A<<smallest_right
    #end
    #if nanor==0
    #    A<<smallest_left
    #end

        #error message points to the line below (rb:44)
    if smallest_left<smallest_right
        A << smallest_left
        print A
        left.pop[i]
    elsif smallest_left>smallest_right
        A << smallest_right
        print A
        right.pop[i]
    else
        print A
    end
end

对于 input = ['z','b','r','a'] 我可以在错误中看到正在排序的列表:

["a"]["a", "b"]["a", "b", "r"] rb:44:in `<': comparison of String with nil failed (ArgumentError)

请帮我看看我的错误:)提前致谢!

最佳答案

发生异常是因为您正在尝试比较 nil。当 nil 在左边时,你会得到一个不同的异常。

'1' < nil
#=> scratch.rb:1:in `<': comparison of String with nil failed (ArgumentError)

nil > '1'
scratch.rb:1:in `<main>': undefined method `>' for nil:NilClass (NoMethodError)

leftright 数组为空时(即它的所有元素都已添加到 A 中),您的代码会遇到这种情况。据推测,这就是您最初为 nanol == 0nanor == 0 添加 if 语句的原因(即处理其中一个数组为空时的情况)。

您的 if 语句有几个问题:

  1. 您确实需要 nanol == 0nanor == 0 语句
  2. 三个 if 语句始终运行,即使在一次迭代中只有一个适用
  3. nanolnanor 永远不会重新计算(即它们永远不会归零)
  4. 当左右值相等时,您实际上并没有向A 数组添加任何内容

迭代的内部应该是:

smallest_left = left.min
smallest_right = right.min

nanol=left.length
nanor=right.length  

if nanol == 0   #Handles left no longer having values
    A << right.delete_at(right.index(smallest_right) || right.length)
elsif nanor == 0    #Handles right no longer having values
    A << left.delete_at(left.index(smallest_left) || left.length)
elsif smallest_left < smallest_right
    A << left.delete_at(left.index(smallest_left) || left.length)
elsif smallest_left > smallest_right
    A << right.delete_at(right.index(smallest_right) || right.length)
else #They are equal so take one
    A << left.delete_at(left.index(smallest_left) || left.length)
end

当您的列表包含奇数个元素时,您仍然会遇到问题(没有错误,但会出现意外结果)。但希望这能回答您的问题。

关于ruby - 二进制字母排序 ruby ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14593132/

相关文章:

arrays - 符合以下条件的 N 长序列对

java - 快速排序算法显示错误的输出

java - 归并排序列表实现TopDown + BottomUp + Abstract MergeSort

ruby - 如何自动命名哈希中的符号?

ruby-on-rails - 直接在模型上调用 rspec 会导致 stub 错误!方法

ruby - 如何使用 define_method 创建类方法?

algorithm - 在线性或亚线性时间内找到 BIT 的最大值和最小值

iphone, 图像处理

ruby - 从表中的类名创建动态变量,将 td 值移动到该行数组或散列中?

java - 在集合末尾添加新行