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 to the 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' increases y , 'SOUTH' decreases y , the same goes for 'EAST' / 'WEST' and x .
In an array example, this gives:
x
They should be transferred back to the array of directions:
[ *Array.new(y.abs) { y.positive? ? 'NORTH' : 'SOUTH' }, *Array.new(x.abs) { x.positive? ? 'EAST' : 'WEST' } ]
Although this is not the shortest code, IMO is relatively easy to understand.
Stefan
source share