Direction Catastrophe

 




We are given directions to go from one point to another. The directions are "NORTH", "SOUTH", "WEST", "EAST". Clearly "NORTH" and "SOUTH" are opposite, "WEST" and "EAST" too. Going one direction and coming back the opposite direction is a wasted effort, so let's concise these directions to go the shortest route. For example, given the following directions: You can immediately see that going "NORTH" and then "SOUTH" is not reasonable, better stay to the same place!


def reduce_dir(directions)
  opposite = { 'NORTH' => 'SOUTH',
               'EAST' => 'WEST',
               'SOUTH' => 'NORTH',
               'WEST' => 'EAST' }
  final_directions = []
  directions.each_with_index do |_value, d|
    if final_directions.length.positive?
      if final_directions[-1] == opposite[directions[d]]
        final_directions.pop
      else
        final_directions << directions[d]
      end
    else
      final_directions << directions[d]
    end
  end
  final_directions
end

# driver code
p reduce_dir(%w[NORTH SOUTH WEST EAST])
p reduce_dir(%w[NORTH SOUTH SOUTH EAST WEST NORTH WEST])

Comments

Popular