我有一个问题,我正在尝试创建一个方向数组,其中每个方向都不是多余的.
plan = ["NORTH","SOUTH","EAST","WEST","NORTH","WEST"]
正如您所看到的,此计划中的大多数值都是多余的,您也可以简单地告诉该人去“西部”.
plan = ["NORTH","EAST"]
我还希望上面的计划返回一个空数组.
解决方法
鉴于一系列方向:
plan = %w[NORTH SOUTH SOUTH EAST WEST NORTH WEST] #=> ["NORTH","WEST"]
我会将方向转换为x和y坐标:
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递减.
使用示例数组,它给出:
x #=> -1 y #=> 0
这些必须转换回一系列方向:
[ *Array.new(y.abs) { y.positive? ? 'NORTH' : 'SOUTH' },*Array.new(x.abs) { x.positive? ? 'EAST' : 'WEST' } ] #=> ["WEST"]
虽然这不是最短的代码,但掌握IMO相对容易.