问题在红宝石二进制搜索算法 [英] Problem with binary search algorithm in ruby

查看:153
本文介绍了问题在红宝石二进制搜索算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  DEF的binarySearch(A,B,找到相当,字符串数组)
  K =(A + B)/ 2
  如果一个== b
    零回报
  结束
  如果(字符串数组[K])。包括哪些内容?找到相当
    返回字符串数组[k]的
  结束
  如果(字符串数组[k]的&下; =>找到相当)== 1
    BinarySearch的(A,K,找到相当,字符串数组)
  结束
  如果(字符串数组[k]的&下; =>找到相当)== - 1
    二分查找(K,B,找到相当,字符串数组)
  结束
  如果(字符串数组[K]< = GT;找到相当)== 0
    返回字符串数组[k]的
  结束
结束

这是一个二进制搜索算法。的a和b是它正在工作的数组索引,找到相当的是它正在搜索的字符串,并且字符串数组是一个字符串数组。不幸的是,每当我尝试运行这个功能,我得到以下语法错误时间:

 未定义的方法`包括哪些内容? 1:Fixnum对象(NoMethodError)`

但是,这不是一个长整数。我是pretty新的Ruby,所以我可以很容易地失去了一些东西明显。任何建议?

这是我在这里声明字符串数组:(Netbeans的说,它是一个数组)

 字符串= Array.new
  newstring =
  直到newstring ==不吗
    newstring = gets.chomp
    字符串[strings.size] = newstring
  结束


解决方案

的传递到你的函数字符串数组实际上不是一个字符串数组,而只是一个简单的串。在一个字符串使用 [] 方法返回给定位置的字符的字符code,作为一个Fixnum对象;所以字符串数组[K]在返回字符串中位置k的字符的字符code。而作为错误说,Fixnum对象不具有<​​code>包括哪些内容?。

即使字符串数组的的字符串数组,我不知道你为什么会做字符串比较与包括哪些内容?包括哪些内容?是找出是否在数组中存在的项目。比较字符串,只需使用 ==

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

解决方案

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

这篇关于问题在红宝石二进制搜索算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆