Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove from the array elements that are repeated

Tags:

arrays

ruby

What is the best way to remove from the array elements that are repeated. For example, from the array

a = [4, 3, 3, 1, 6, 6]

need to get

a = [4, 1]

My method works to too slowly with big amount of elements.

arr = [4, 3, 3, 1, 6, 6]
puts arr.join(" ")
nouniq = []
l = arr.length
uniq = nil
for i in 0..(l-1)
  for j in 0..(l-1) 
    if (arr[j] == arr[i]) and ( i != j )
      nouniq << arr[j]
    end
  end
end
arr = (arr - nouniq).compact

puts arr.join(" ")
like image 787
user678249 Avatar asked Dec 07 '25 04:12

user678249


1 Answers

a = [4, 3, 3, 1, 6, 6]
a.select{|b| a.count(b) == 1}
#=> [4, 1]

More complicated but faster solution (O(n) I believe :))

a = [4, 3, 3, 1, 6, 6]
ar = []
add = proc{|to, form| to << from[1] if form.uniq.size == from.size }
a.sort!.each_cons(3){|b| add.call(ar, b)}
ar << a[0] if a[0] != a[1]; ar << a[-1] if a[-1] != a[-2]
like image 136
fl00r Avatar answered Dec 08 '25 18:12

fl00r



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!