Jack Kelly Jack Kelly - 6 months ago 27
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

plan = ["NORTH", "WEST", "SOUTH", "EAST"]

I also want the plan above to return an empty array.

ndn ndn
  'NORTH' => 'SOUTH',
  'WEST'  => 'EAST',
  'EAST'  => 'WEST',
  'SOUTH' => 'NORTH',

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

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

  [direction] * [uncounteracted_occurances, 0].max