【问题标题】:Why is the method deleting the element inside my array?为什么该方法会删除我的数组中的元素?
【发布时间】:2014-08-13 02:03:19
【问题描述】:

我正在尝试使用递归创建自己的 .sort 方法作为红宝石书中的练习,但由于某种原因,他们还没有教我宇宙飞船操作员。我的代码用于获取最小值 - 苹果 - 并将其放入排序数组中,它甚至使用递归重复,并重置数组以重复添加第二小的单词的过程。问题是由于某种原因它删除了最小的单词-apple-,我不知道为什么。我知道我的想法 - 在 else myArray.length == 1 语句中,当我将元素从数组中弹出时,但为什么它也从 sortedArray 中删除?

sortedArray 以值 apple 结束,然后当它进行递归时,它应该是 sortedArray = ['apple', 'banana' ...] 但它删除了苹果,然后它删除了香蕉等......直到我最终得到 sortedArray = ['昆西']

我尝试将我的数组移动到多个位置,并且我尝试在多个位置添加到 sortedWords 数组,但它总是删除或重置 sortedWords 数组。

看起来我真的很接近,因为我已经完成了字母排序工作。如何让它将所有项目添加到 sortedWords 数组?

ArrayofWords = ['cat', 'dog', 'bat', 'elephant', 'apple', 'banana', 'quincy', 'boo']

# Why is it deleting, or replacing my sortedWords array? If you run this code you will     notice that the sortedWords array
# is giving me the smallest word in the array, but then I add the recursive part, and somehow the previous smallestword
#gets deleted... but I have never in any part of my code say delete or replace the sorted    array...

def sortTheArray myArray
  unsortedWords = []
  sortedWords   = []
  smallestValue = ''

  while myArray.length != 0
    if myArray.first < myArray.last
      unsortedWords.push(myArray.last)
        myArray.pop
    elsif myArray.first > myArray.last
      unsortedWords.push(myArray.first)
      myArray.delete_at(0)
    else myArray.length == 1
      sortedWords.push(myArray.first)
      myArray.pop # This is my problem area I think???
    end # if else


    #puts 'sorted words'  
    #puts sortedWords
    #puts 'unsortedWords'
    #puts unsortedWords
  end # while

  puts 'sorted words'  
  puts sortedWords
  puts 'unsortedWords'
  puts unsortedWords

  myArray = unsortedWords

  while myArray.length > 0
    sortTheArray myArray
  end #while

end # sortTheArray
sortTheArray ArrayofWords

大部分puts都没有必要,我只是想弄清楚问题出在哪里。

【问题讨论】:

  • 对不起,开头写错了标题。昨晚我在问一个问题,它保存了,所以我忘了改标题。

标签: ruby arrays sorting


【解决方案1】:

您的代码存在许多问题。例如,您似乎希望在此方法的调用中累积排序的单词,但您在方法块的开头将 sorted_words 重新初始化为 []

我建议首先尝试用英语尽可能简单地表达您的递归解决方案,然后再尝试实现它。

例如,以下是一种似乎与您尝试做的事情一致的方法:

def sorted_array(array)
  lowest_value prepended to the sorted_value of the array with the lowest_value removed
end

我之所以分享上述内容,是因为您似乎是 Ruby 的新手,并且以惯用的方式实现上述内容将是一个很好的挑战。

【讨论】:

  • 好的。这很有意义。需要一些时间来消化你所说的。我可能可以从这里弄清楚,但需要一些时间。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 2021-11-28
  • 2023-03-11
  • 2022-08-03
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多