multisetDifference<T> function

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

Returns the multiset difference a minus b, subtracting counts and dropping any element whose remaining count falls to zero or below.

Implementation

Map<T, int> multisetDifference<T>(Map<T, int> a, Map<T, int> b) {
  final Map<T, int> out = Map<T, int>.from(a);
  for (final MapEntry<T, int> e in b.entries) {
    final int cur = out[e.key] ?? 0;
    final int r = cur - e.value;
    if (r <= 0) {
      out.remove(e.key);
    } else {
      out[e.key] = r;
    }
  }
  return out;
}