math - How do I return the intersection of two lists including duplicates in mathematica? -
how find intersection of 2 lists including duplicates in mathematica?
so, if have this:
list1 = {1, 1, 3, 4, 5, 6, 6, 6, 7, 7, 10, 11, 11}; list2 = {1, 1, 4, 5, 5, 6, 6, 7, 7, 8, 11, 11, 13, 14};
i'd want return this:
intersectionincludingduplicates[list1, list2] = {1, 1, 4, 5, 6, 6, 7, 7, 11, 11}
thanks , help!
here's 1 way:
catenate@keyvaluemap[constantarray]@ mapthread[min, keyintersection[counts /@ {list1, list2}]]
breaking down:
- count how many times each element occurs in each list (
counts
) - retain elements occur in both (
keyintersection
) - take smaller number of occurrences (
mapthread
,min
) , replicate given element many times (constantarray
)
Comments
Post a Comment