简体   繁体   English

红宝石中二进制搜索算法的问题

[英]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. a和b是它正在处理的数组索引,tofind是它正在搜索的字符串,stringarray是一个字符串数组。 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. 但这不是一个fixnum。 I am pretty new to Ruby, so I could easily be missing something obvious. 我是Ruby的新手,所以我很容易错过明显的东西。 Any advice? 有什么建议吗?

This is where I declare stringarray: (Netbeans says that it is an array) 这是我声明stringarray的地方:(Netbeans说这是一个数组)

  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. 传递给您的函数的stringarray实际上不是字符串数组,而仅仅是一个简单的字符串。 Using the [] method on a string returns the character code of the character at the given position, as a Fixnum; 在字符串上使用[]方法会返回给定位置的字符的字符代码,即Fixnum。 so stringarray[k] returns the character code of the character at position k in the string. 因此stringarray [k]返回字符串中位置k处的字符的字符代码。 And as the error says, Fixnum does not have an include? 并且如错误所述,Fixnum没有include? .

Even if stringarray was an array of strings, I'm not sure why you would do string comparisons with include? 即使stringarray 字符串数组,我也不知道为什么要使用include?进行字符串比较include? . include? is for finding out if items exist in an array. 用于确定数组中是否存在项。 To compare strings, just use == . 要比较字符串,只需使用==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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