Ruby - array intersection (with duplicates)

前端 未结 6 830
一生所求
一生所求 2021-01-02 11:23

I have array(1 and 2). How can I get array3 from them?

array1 = [2,2,2,2,3,3,4,5,6,7,8,9]

array2 = [2,2,2,3,4,4,4,4,8,8,0,0,0]

ar         


        
6条回答
  •  甜味超标
    2021-01-02 11:59

        array1 = [2,2,2,2,3,3,4,5,6,7,8,9]
        array2 = [2,2,2,3,4,4,4,4,8,8,0,0,0]
    

    Getting the frequency of each element in the sample arrays:

        a1_freq=Hash.new(0); a2_freq=Hash.new(0); dup_items=[];
        array1.each {|a| a1_freq[a]+=1 }
        array2.each {|b| a2_freq[b]+=1 }
    

    Finally compare the elements if they are present in the other array or not. If yes, then take minimum count of the common element found in both sample arrays.

        a1_freq.each {|k,v| a2_freq[k] ? dup_items+=[k]*[v,a2_freq[k]].min : nil}
        #dup_items=> [2, 2, 2, 3, 4, 8]
    

提交回复
热议问题