How many times does array appear in another array?

Richard

New Member
#1
I'm new to Ruby on Rails. This question seems to be answered in other programming languages but not RoR.

I have an array with 3 items in it.
Mã:
array1 = [1, 2, 3]
I then have items in another array which i want to check and see how many times array1 appear in array2:
Mã:
array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 10, 11, 2, 12, 3]
Answer should be 2.
 

Admin

Administrator
Thành viên BQT
#2
You can try the following:
Mã:
a1.map { |a1i| a2.count(a1i) }.min
which is calculating how frequently each item in array1 appears in array2 and then fetching the minimum count as the number of possible subarrays without intersections.

A sketchy representation of what my perception of @Stefan's suggestion is:
Mã:
a1.product([0]).to_h.merge(
  a2.group_by(&:itself).transform_values(&:size)
).values_at(*a1).min
And a more reasonable one:
Mã:
count_per_a2i = a2.group_by(&:itself).transform_values(&:size)
a1.map { |a1i| count_per_a2i[a1i] }.compact.min
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top