multisetIntersection<T> function

Map<T, int> multisetIntersection<T>(
  1. Map<T, int> a,
  2. Map<T, int> b
)

Returns the multiset intersection of a and b, keeping each shared element with the minimum of its two counts. Elements absent from either input are omitted.

Implementation

Map<T, int> multisetIntersection<T>(Map<T, int> a, Map<T, int> b) {
  final Map<T, int> out = <T, int>{};
  for (final MapEntry<T, int> e in a.entries) {
    final int vb = b[e.key] ?? 0;
    if (vb > 0) out[e.key] = e.value < vb ? e.value : vb;
  }
  return out;
}