开发者

Problem with binary search algorithm in ruby

def binarysearch(a, b,  tofind, stringarray)
  k=(a+b)/2
  if a==b
    return nil
  end
  if (stringarray[k]).include? tofind
    return stringarray[k]
  end
  if (stringarray[k]<=>tofind)==1
    binarysearch(a,k,tofind,stringarray)
  end
  if (stringarray[k]<=>tofind)==-1
    binarysearch(k,b,tofind,stringarray)
  end
  if (stringarray[k]<=>tofind)==0
    return stringarray[k]
  end
end

This is a binary search algorithm. The a and b are the array indices that it is working on, tofind is a string that it is searching for, and stringarray is an array of strings. Unfortunately, every time that I try to run this function I get the following syntax error:

undefined method `include?' for 1:Fixnum (NoMethodError)`

But this is not a fixnum. I am pretty new to Ruby, so I could easily be missing something obvious. Any advice?

This is where I declare stringarray: (Netbeans says that it is an array)

  strings=Array.new
  newstring=""
  until newstring=="no" do
    newstring=gets.chomp
    strings[strings.size]=newstring开发者_JS百科
  end


This adds binary search to all arrays:

class Array
  def binarysearch(tf,lower=0,upper=length-1)
    return if lower > upper
    mid = (lower+upper)/2
    tf < self[mid] ? upper = mid-1 : lower = mid+1
    tf == self[mid] ? mid : binarysearch(tf,lower,upper)
  end
end

Then you can use it like this:

(0..100).to_a.binarysearch(25)
=> 25
(0..100).to_a.binarysearch(-1)
=> nil

Or specify your lower and upper bound from the beginning:

(0..100).to_a.binarysearch(25, 50, 100)
=> nil


The stringarray that is passed to your function is not actually an array of strings, but just a simple string. Using the [] method on a string returns the character code of the character at the given position, as a Fixnum; so stringarray[k] returns the character code of the character at position k in the string. And as the error says, Fixnum does not have an include?.

Even if stringarray was an array of strings, I'm not sure why you would do string comparisons with include?. include? is for finding out if items exist in an array. To compare strings, just use ==.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜