Skip to content

Instantly share code, notes, and snippets.

@ahmadhasankhan
Last active November 19, 2017 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadhasankhan/a5cbdf500bc7a56a2aec171f95bd0080 to your computer and use it in GitHub Desktop.
Save ahmadhasankhan/a5cbdf500bc7a56a2aec171f95bd0080 to your computer and use it in GitHub Desktop.
Write a function which accepts an integer array and its size and modifies the array in the following manner.
# 1) If the elements of index i and (i+1) are equal then, double the value at index i
# and replace the element at index (i+1) with 0.
# 
#     2) If the element at index i is 0, then ignore it.
# 
#     3) Any number (element in an array) must be modified only once.
# 
#     4) At the end, shift all the zeros (0s) to the right of the array and remaining
# nonzeros to the left of the array.
# 
#     Example:
#     Input: 2 2 0 4 0 8
# Output: 4 4 8 0 0 0
# 
# Input: 2 2 0 4 0 2
# Output: 4 4 2 0 0 0
def modify_array(*arr)
  @result = arr
  @result.each_with_index do |el, i|
    if el == 0
      next
    elsif is_integer?(el) && el == @result[i+1]
      @result[i] = @result[i] * 2
      @result[i+1] = 0
    end
  end
  shift_zeros_to_end
end

def is_integer?(value)
  value.is_a? Integer
end

def shift_zeros_to_end
  len = @result.length
  count = 0

  @result.each do |el|
    unless el == 0
      @result[count] = el
      count += 1
    end
  end

  while count < len
    @result[count] = 0
    count += 1
  end

  @result
end

modify_array(2, 2, 0, 4, 0, 2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment