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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With