Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.