Jack Kelly Jack Kelly - 2 months ago 6
Ruby Question

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.

ndn ndn
Answer
OPPOSITES = {
  'NORTH' => 'SOUTH',
  'WEST'  => 'EAST',
  'EAST'  => 'WEST',
  'SOUTH' => 'NORTH',
}

frequencies = plan.group_by(&:itself).map do |direction, occurrences|
  [direction, occurrences.size]
end.to_h

OPPOSITES.flat_map do |direction, opposite_direction|
  uncounteracted_occurances =
    frequencies[direction] - frequencies[opposite_direction]

  [direction] * [uncounteracted_occurances, 0].max
end