Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby index of array elements

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
like image 884
Aparichith Avatar asked Mar 12 '26 23:03

Aparichith


2 Answers

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.

like image 195
Pengcheng Zhou Avatar answered Mar 15 '26 12:03

Pengcheng Zhou


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.

like image 40
ray Avatar answered Mar 15 '26 11:03

ray



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!