简体   繁体   中英

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
  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 == .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM