如何从数组中删除相反的值? [英] How do I remove opposite values from an array?
问题描述
我遇到一个问题,我试图创建一个方向数组,每个方向都不是多余的.
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.
推荐答案
给出一系列方向:
plan = %w[NORTH SOUTH SOUTH EAST WEST NORTH WEST]
#=> ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
我会将方向转换为 x
和 y
坐标:
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'
递增 y
,'SOUTH'
递减 y
,与'EAST相同'
/'WEST'
和 x
.
'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"]
尽管这不是最短的代码,但是它相对容易掌握IMO.
Although this is not the shortest code, it's relatively easy to grasp IMO.
这篇关于如何从数组中删除相反的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!