ruby - 在没有排序功能的情况下对数组中的字符串进行排序 - Ruby

标签 ruby algorithm sorting insertion-sort

我正在尝试创建一个没有 Ruby 中排序函数的排序算法。我基于插入排序的想法。这个想法是该函数检查每两个单词的第 n 个值是否相同,如果相同,则 n 增加 1,直到一个值大于另一个。在那种情况下,单词可能会被调换。但是,我的功能一直卡住。有什么想法吗?

words = ["my","favorite","animal", "are", "the", "elephant", "and", "the", "antelope", "and", "the", "favela"]

#Convert all letters into numbers. Output individual words as arrays.
converted_words = words.map(&:chars).map { |letters| letters.map { |letter| letter.to_i 36 } }
puts converted_words.to_s

i = 1
x = 0
while i < converted_words.length
  if converted_words[i][x] == converted_words[i-1][x]
    x = x + 1
  else
    if converted_words[i][x] < converted_words[i-1][x]
      converted_words[i], converted_words[i-1] = converted_words[i-1], converted_words[i]
      i = 0
      x = 0
    else
      i = i + 1
    end
  end
end
puts converted_words.to_s

最佳答案

您的代码不会“卡住”;运行它会引发此异常:

NoMethodError (undefined method '<' for nil:NilClass)

行内:

if converted_words[i][x] < converted_words[i-1][x]

我们立即发现问题,但原因尚不清楚。方法的接收者<converted_words[i][x] .正如错误消息所说 nil没有方法 < , 我们推断 converted_words[i][x]nil .1 这意味着索引超出范围(索引超出范围的示例是 [1,2][412] #=> nil[1,2][-3] #=> nil )。如果i如果超出范围,表达式将减少为 nil[x] < ... ,这将引发一个异常 nil没有方法 NilClass#\[\]] .这不是我们的异常消息,因此我们得出结论 x必须超出范围。

要了解为什么会发生这种情况,假设:

words = ["a", "ab"]

然后

converted_words =
  words.map(&:chars).map { |letters| letters.map { |letter| letter.to_i 36 } }
  #=> [[10], [10, 11]] 
i = 1
x = 0
while i < converted_words.length
  #=> while 1 < 2 => while true, so enter the loop
if converted_words[i][x] == converted_words[i-1][x]
  #=> if converted_words[1][0] == converted_words[0][0] => if 10 == 10 => true

所以执行

x = x + 1
  #=> x = 0 + 1 => 1

并尝试重复循环。

while i < converted_words.length
  #=> while 1 < 2 => while true, so repeat the loop
if converted_words[i][x] == converted_words[i-1][x]
  #=> if converted_words[1][1] == converted_words[0][1] => if 11 == nil => false

所以执行(else)。

if converted_words[i][x] < converted_words[i-1][x]
  #=> converted_words[0][1] < converted_words[-1][1] => if nil < 11
  #=> NoMethodError (undefined method '<' for nil:NilClass)

错误消息包含有值(value)的信息。仔细研究它们!

1 错误消息“nil 没有方法 <”在这里等同于“NilClass 没有实例方法 <”。

关于ruby - 在没有排序功能的情况下对数组中的字符串进行排序 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52875660/

相关文章:

algorithm - 基于文档重要性的句子排序算法

algorithm - 我无法在尝试解决 spoj stavatar 的算法中找到错误

python - 如何对坐标列表进行排序?

ruby - 在 Ruby 中对字符串和数字进行排序

ruby-on-rails - 如何在 Rails 脚手架生成器上强制使用单数表名?

ruby-on-rails - Elasticsearch 的多方面过滤器

algorithm - 如何最好地在 R 中创建定时器函数

java - 排序和重新排列(不同的)数组

algorithm - 证明合并排序输出输入的排列

ruby-on-rails - PG::UndefinedColumn:错误:列 photos.attachable_type 不存在