Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove opposite values from an array?

Tags:

arrays

ruby

I have a problem where I am trying to create an array of directions in which each direction is not redundant.

plan = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

As you can see most of the values in this plan are redundant and you may as well simply tell the person to go "WEST".

plan = ["NORTH", "WEST", "SOUTH", "EAST"]

I also want the plan above to return an empty array.

like image 920
Jack Kelly Avatar asked Sep 28 '16 12:09

Jack Kelly


1 Answers

Given an array of directions:

plan = %w[NORTH SOUTH SOUTH EAST WEST NORTH WEST]
#=> ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]

I would translate the directions into x and y coordinates:

x, y = 0, 0

plan.each do |direction|
  case direction
  when 'NORTH' then y += 1
  when 'EAST'  then x += 1
  when 'SOUTH' then y -= 1
  when 'WEST'  then x -= 1
  end
end

'NORTH' increments y, 'SOUTH' decrements y, same for 'EAST' / 'WEST' and x.

With the example array this gives:

x #=> -1
y #=> 0

These have to be translated back to an array of directions:

[
  *Array.new(y.abs) { y.positive? ? 'NORTH' : 'SOUTH' },
  *Array.new(x.abs) { x.positive? ? 'EAST' : 'WEST' }
]
#=> ["WEST"]

Although this is not the shortest code, it's relatively easy to grasp IMO.

like image 169
Stefan Avatar answered Nov 21 '22 06:11

Stefan