0

In [[1,2],[2,1],[8,9],[12,12]], the first two elements are same. I want to get an output like this: [[8,9],[12,12]].

In:

[1,2,3].product([1,2,3])
# => [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

I want to get an output like this:

[[1, 1], [2, 2], [3, 3]]

2 Answers 2

2

To get unique output irrespective of individual Array's arrangement, do this:

[1,2,3].product([1,2,3]).map(&:sort).uniq
#  => [[1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3]]

If you require output with only repetitive values, do this:

[1,2,3].product([1,2,3]).map {|k,v| [k,v] if k == v}.compact
# => [[1, 1], [2, 2], [3, 3]]
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think that's what he's looking for. Your answer does not work for his first test case (returns [[12,12]] instead of [[8,9],[12,12]]).
@dwenzel It sure does, please recheck. [[12,12]] will be returned for 2nd case. 1st case returns [[1, 2], [8, 9], [12, 12]]. You may say [1, 2] is extra, but the objective here is to point OP in right direction. he can easily remove that if required.
See my answer. I think for both of his test cases, he wants to remove any elements that have duplicates, including the duplicate and original. In his second case, it's only a coincidence that all remaining elements happen to have repetitive values. @JunanChakma , can you confirm?
1

Ruby does have a #uniq method, but that removes any duplicates but KEEPS one of them. So that will not work in your case, since it appears that you're looking to remove ALL elements that have duplicates.

Here's a solution that should do the trick:

def remove_dups(array)
  new_array = []
  # first, sort each element
  start_array = array.map{|e| e.sort}
  start_array.each_with_index do |sub_array, idx|
    temp_array = start_array.dup
    temp_array.delete_at(idx)
    # after deleting the element, check to see if the array still includes the element
    new_array << sub_array unless temp_array.include?(sub_array)
  end
new_array
end

p remove_dups([[1,2],[2,1],[8,9],[12,12]])
#=> [[8, 9], [12, 12]]
p remove_dups([1,2,3].product([1,2,3]))
#=> [[1, 1], [2, 2], [3, 3]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.