Swapping elements in an array with Ruby and JavaScript

Given an array of negative/positive integers, swap the smallest element of the array with the first element of the array.

Ruby: version 1 (cumbersome, but works)

array = [ 4, 3, 0, 2, 2 ]

def min(array)
  if array.length == 0
    nil
  end
  smallest = array.first
  array.each do |element|
    if smallest > element
      smallest = element
    end
  end
  smallest
end

smallest = min(array)

if smallest == array.first
  array
else
  hash = Hash[array.map.with_index.to_a]
  index = hash[smallest]
  array.slice!(index, 1)
  first = array.shift
  array.insert(index - 1, first)
  array.unshift(smallest)
  array
end

puts "The swapped array is #{array}"
# The swapped array is [0, 3, 2, 4, 2]

Ruby: version 2 (A shorter way)

array = [ 9, 4, 3, 1, 12, 5, 21 ]

def swap(array)
  # 1. We get the smallest element with this hacky method.
  smallest = array.min
  # 2. Then, if the smallest is already the first element,
  #    just return the array as is. Not modified.
  if smallest == array.first
    array
  else
    # 3. If not, 'first' will be the first element in the array.
    #    The method shift(), takes the first element in an array
    #    returns it.
    first = array.shift
    # 4. We convert the array into a hash to find the index faster.
    #    We could use the method 'include()', but it is really inefficient
    #    because it has to iterate through the whole array and compare
    #    each element with the given one to see if it matches.
    hash = Hash[array.map.with_index.to_a]
    # 5. Then we get the index using hash[smallest].
    index = hash[smallest]
    # 6. We destructively remove the first element in the array.
    #    The method slice has two parameters, the first one is the
    #    starting position where it will start to be applied, and
    #    the second parameter is the amount of elements we plan to
    #    remove starting from the position in the first parameter.
    #    In other words, cut one position in the array starting from
    #    position 3.
    array.slice!(index, 1)
    # 7. Then insert the first element of the array in that position.
    array.insert(index, first)
    # 8. Then put the smallest element in the first position.
    #    Note that 'shift()' cuts the first element, I bet is easy to 
    #    guess what 'unshift()' does.
    #    If you guessed it adds an element to the first position, you
    #    are right.
    array.unshift(smallest)
    # 9. Finally, we return the modified array.
    array
  end
end

puts "The swapped array is #{swap(array)}"
# The swapped array is [1, 4, 9, 3, 12, 5, 21]

Ruby: version 3 (A “better” way)

array = [ 9, 4, 1, 3, 12, 5, 0 ]

def small_swap(array)
  # 1. We declare the variables
  small_index = 0
  small_element = array.first

  # 2. Using a for loop we iterate from 0 to the length of 
  #    the array, being 'i' the current index
  for i in 0...array.length
    # 3. If 'small_element' is greater than the current element
    if small_element > array[i]
      # 4. then, the value of 'small_element' will become the 
      #    value of the current element
      small_element = array[i]
      # 5. We set the value of 'small_index' to i
      small_index = i
    end
  end
  # 6. Now, the value of the element positioned in the 
  #    index of the smallest one will become the first element,
  #    in this case, array[6] (the seventh position) will become 9
  array[small_index] = array[0]
  # 7. And the first element will become the smallest,
  #    in this case, array[0] will be 0
  array[0] = small_element
  # 8. Lastly, we return the modified array.
  array
end

puts "The swapped array is #{small_swap(array)}"
# The swapped array is [0, 4, 1, 3, 12, 5, 9]

Now it’s time to take a look at how this could be done with JavaScript:

JavaScript: version 1

var array = [ 18, 4, 3, 5, 22, 12 ];

function swap(array) {
  // 1. We declare the variables
  var smallest = array[0];
  var index = 0;
  // 2. Using a "For Loop", we iterate through the array
  for (var i = 0, x = array.length; i < x; i += 1) {
    // 3. We define 'current' as current element in every iteration
    var current = array[i];
    // 4. If 'smallest', which is the variable we defined before the loop is
    //    bigger than the 'current' element, then the value of 'smallest' will 
    //    become the value of current. When we finish the iteration, the smallest
    //    element in the array will become the value of 'smallest'.
    if (smallest > current) {
      smallest = current;
      // 5. We set the value of 'index' as 'i', this changes the value of the 
      //    var index we defined before. That way we can get the value of 'i' 
      //    from outside the loop.
      index = i;
    } 
  }
  // 6. We log the values just to make sure we got the correct ones. In this case: |
  console.log(smallest + " " + index); // <-- smallest is 3, and index is 2 <----- |
  // 7. We remove from the array one element starting in index 2, that means we
  //    remove the 3, which is 'smallest', and we add the first element of the array
  //    in that position.
  array.splice(index, 1, array[0]);
  // 8. Then, we remove the first element in the array and insert 3 in its position.
  array.splice(0, 1, smallest);
  // 9. Finally we return the modified array.
  return array;
}

console.log("The swapped array is " + swap(array));
// The swapped array is 3,4,18,5,22,12

JavaScript: version 2

var array = [ 43, 34, -12, 678, 95, 65, -212, -137 ];

function small_swap(array) {
  // 1. We declare the variables
  var smallest = array[0];
  var index = 0;
  var i = 0;
  // 2. Using a 'while loop' we iterate through the array
  while (i < array.length) {
    // 3. If the current element is less than 'smallest'
    if (array[i] < smallest) {
      // then 'smallest' will become the current element
      smallest = array[i];
      // 4. We set the value of 'index' as 'i', this changes the value of the 
      //    var index we defined before. That way we can get the value of 'i' 
      //    from outside the loop.
      index = i;
    }
    // 5. Now we update the value of i to avoid an infinite loop.
    i += 1;
  }
  // 6. We log the values just to make sure we got the correct ones. In this case: |
  console.log(smallest + " " + index); // <-- smallest is -212, and index is 6 <-- |
  // 7. Now the value in the 7th position in the array, which is array[6] will become
  //    the whatever value we had in the first position (array[0]). 
  array[index] = array[0];
  // 8. And the value of the first position, will become the smallest element we
  //    found in the array.
  array[0] = smallest;
  // 9. Finally we return the modified array.
  return array;
}

console.log("The swapped array is " + small_swap(array));
// The swapped array is -212,34,-12,678,95,65,43,-137

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s