Daniel Bonnell
Daniel Bonnell

Reputation: 4997

Swap adjacent elements in array

I am trying to build a method in Ruby that will take in a string that has been split into an array of letters and then iterate through the array, swapping the element at index n with that at index n+1. The method will then join the new array into a string and push it to another array.

Here is an example of what I am looking to do:

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

Expected output:

["eth", "the"]

This is for a spell checker program I am writing for school. The method will check if letters in a misspelled word are swapped by checking to see if the output array elements are in the dictionary. If they are, it will return the word with that is most likely the correct word. I haven't had any luck finding articles or documentation on how to build such a method in ruby or on an existing method to do this. I've been tinkering with building this method for awhile now but my code isn't behaving anything like what I need. Thanks in advance!

Upvotes: 1

Views: 3845

Answers (2)

raph
raph

Reputation: 470

Without splitting it into arrays then joining to new arrays (because that doesn't seem necessary):

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

Upvotes: 1

Cary Swoveland
Cary Swoveland

Reputation: 110675

As @Sergio advised, you want to use parallel assignment for this:

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

Upvotes: 1

Related Questions