I am facing challenge to improve performance in my code. Here is the problem
matcher = [ [1,2], [3,4], [6,7] ]
elements_array = [1,2,3,4,5,6,7,8]
from above data, I need to create combination data in specific format and then match with matcher.
data_to_create = [[1],[1,2], [1,2,3], [1,2,3,4,5], [1,2,3,4,5,6], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8], [2], [2,3], [2,3,4], [2,3,4,5]... [8] ]
Now I need to iterate data_to_create
and check that any element has combination of matcher ? for example [1,2,3,4,5]
will not consider as [3,4]
is in matcher and so can't be in same set.
I have fixed above scenario but have issue with performance. So looking for solution. Here is solution :
n = 8
total_data = (1..n).to_a
matchers = [ [1,2], [3,4], [6,7],[7,8] ]
total_data.each_with_index do |i, index|
(n - index).times do |j|
element = total_data[index..(index + j )]
if !matchers.detect{|e| (e - element).empty? }
valid_data << element
else
break
end
end
end
puts valid_data.size
Above solution doesn't work if I have too many matchers e.g. 500 matcher elements and 1500 elements array. I want to improve code to make it working for every scenario in less than 10 seconds.
Aucun commentaire:
Enregistrer un commentaire