二进制字母排序红宝石

时间:2013-01-29 22:19:39

标签: 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)

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

1 个答案:

答案 0 :(得分:1)

发生异常是因为您正在尝试比较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数组添加任何内容
  5. 迭代的内部应该是:

    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
    

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