交换数组中的相邻元素

时间:2014-11-17 18:53:27

标签: ruby arrays swap

我正在尝试在Ruby中构建一个方法,该方法将接收一个已拆分为字母数组的字符串,然后遍历数组,将索引为n的元素与索引n + 1处的元素进行交换。然后,该方法将新数组连接到一个字符串中,并将其推送到另一个数组。

以下是我要做的一个例子:

string = "teh"
some_method(string)
  some ruby magic here
  array << new_string
end

预期产出:

["eth", "the"]

这是我为学校写的拼写检查程序。该方法将通过检查输出数组元素是否在字典中来检查拼写错误的单词中的字母是否被交换。如果是,它将返回单词,这很可能是正确的单词。我没有幸运地找到关于如何在ruby中或在现有方法上构建这样的方法的文章或文档来做到这一点。我一直在修改这个方法一段时间,但我的代码并没有像我需要的那样表现。提前谢谢!

2 个答案:

答案 0 :(得分:1)

不将其拆分为数组然后加入新数组(因为这似乎没必要):

def some_method(string)
  swapped_strings = []
  (0...string.size-1).each do |i|
    temp_string = string.dup
    temp_string[i], temp_string[i+1] = temp_string[i+1], temp_string[i]
    swapped_strings << temp_string
  end
  swapped_strings
end

答案 1 :(得分:1)

正如@Sergio建议的那样,你想为此使用并行分配:

def reverse_em(str)
  (0...str.size-1).map do |i|
    s = str.dup
    s[i], s[i+1] = s[i+1], s[i]
    s
  end
end

candidates = reverse_em "alogrithm"
  #=> ["laogrithm", "aolgrithm", "algorithm", "alorgithm",
  #    "alogirthm", "alogrtihm", "alogrihtm", "alogritmh"]

dictionary_check(candidates)
  #=> algorithm
  #   al·go·rithm
  #   noun \ˈal-gə-ˌri-thəm\
  #   a set of steps that are followed in order to solve a
  #   mathematical problem or to complete a computer process