Ruby - array intersection (with duplicates)

前端 未结 6 803
一生所求
一生所求 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 12:03

    This is a bit verbose, but assuming you mean where the values are at the same position:

    def combine(array1, array2)
        longer_array = array1.length > array2.length ? array1 : array2
    
        intersection = []
        count = 0
        longer_array.each do |item|
            if array1 == longer_array
                looped_array = array2
            else
                looped_array = array1
            end
            if item == looped_array[count]
                intersection.push(item)
            end
            count +=1
        end
        print intersection
    end
    
    
    array_1 = [2,2,2,2,3,3,4,5,6,7,8,9]
    array_2 = [2,2,2,3,4,4,4,4,8,8,0,0,0]
    
    
    combine(array_1, array_2)
    

    I just wanted to point out that I have no clue how you got to array 3 because index position 3 on all three arrays differ:

    array_1[3] = 2
    
    array_2[3] = 3
    
    array_3[3] = 3
    

提交回复
热议问题