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

编程入门 行业动态 更新时间:2024-10-07 20:30:48
本文介绍了问题在红宝石二进制搜索算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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对象不具有包括哪些内容?。

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

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

更多推荐

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

本文发布于:2023-11-29 02:24:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644920.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:红宝石   算法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!