Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove redundant or duplicate tuples in Ruby array

Imagine the following Ruby array:

[9, 9, 5, 5, 5, 2, 9, 9]

What's the easiest way of removing redundant tuples, producing an output like the following:

[9, 5, 2, 9]

uniq is not correct because it's examining the entire array. The ordering of the input is important and must be kept. Is there a straightforward approach to this?

Thanks!

like image 408
aardvarkk Avatar asked Mar 10 '26 03:03

aardvarkk


2 Answers

I'd do using Enumerable#chunk

2.0.0-p0 :001 > a = [9, 9, 5, 5, 5, 2, 9, 9]
 => [9, 9, 5, 5, 5, 2, 9, 9] 
2.0.0-p0 :002 > a.chunk { |e| e }.map(&:first)
 => [9, 5, 2, 9]
like image 141
Arup Rakshit Avatar answered Mar 12 '26 21:03

Arup Rakshit


I would do it like

b = [];
a.each { |n| b << n if b.last != n }

and b is the result

only one array scan is needed

like image 31
xlembouras Avatar answered Mar 12 '26 19:03

xlembouras



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!