Consider I have an array of integer elements. In which I am trying to find the index where a long sequence of repetitive numbers begins.
my_array = [100, 101, 100, 102, 100, 100, 101, 100, 250, 251, 253, 260, 250, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 120]
Bellow is the way I am trying to find the index. Can anyone suggest me more optimised and correct way of doing it?
my_array.each with_index do |e, x|
match = e.to_s * 5
next_10 = my_array[x + 1, 5].join()
if match == next_10
puts "index #{x}"
break
end
end
#index 14
my_array.index.with_index{|value,index| my_array[index,6].uniq.size==1}
This is a kind of tweak, if you mean "optimised" just in the way code looks like.If you mean optimised performance. it does not fit.
In first iteration, I am getting array of repeating elements sequence and then I proceed further with logic,
groups = my_array[1..-1].inject([[my_array[0]]]) { |m, n| m.last[0] == n ? m.last << n : m << [n]; m }
# => [[100], [101], [100], [102], [100, 100], [101], [100], [250], [251], [253], [260], [250], [200], [100, 100, 100, 100, 100, 100, 100, 100, 100], [120]]
groups[0,groups.index(groups.sort { |a,b| a.count <=> b.count }.last)].flatten.count
# => 14
Using regex, it can be precise and simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With