Reputation: 651
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]]
Upvotes: 0
Views: 80
Reputation: 1434
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]]
Upvotes: 1
Reputation: 16506
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]]
Upvotes: 2