Map Multiset Intersection Counts Overlap

Intersect two count bags with min-per-item so shared stock reflects overlapping quantities, not just which names both maps contain.

GoData Integrity

Code

gosnippet
32 lines
package main

import (
	"fmt"
	"sort"
)

// multisetIntersection counts how many of each item the two bags share.
func multisetIntersection(a, b map[string]int) map[string]int {
	out := make(map[string]int)
	for item, count := range a {
		if other, ok := b[item]; ok {
			out[item] = min(count, other)
		}
	}
	return out
}

func main() {
	sold := map[string]int{"antenna": 3, "router": 2, "cable": 5}
	stocked := map[string]int{"router": 4, "cable": 1, "antenna": 3}

	shared := multisetIntersection(sold, stocked)
	names := make([]string, 0, len(shared))
	for name := range shared {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		fmt.Printf("%s: %d\n", name, shared[name])
	}
}

The mechanics of this demo — Map Multiset Intersection Counts Overlap

Map Multiset Intersection Counts Overlap is built around the functions multisetIntersection and main.

Iteration happens inside for item, count := range a — everything outside it runs once.

Points of care

  • Package managers stay out of the picture: each call lands on a built-in API.

Putting it to use

Signature: func multisetIntersection(a, b map[string]int) map[string]int

main calls 1 helper in sequence: multisetIntersection.

Core lines

func multisetIntersection(a, b map[string]int) map[string]int {
	out := make(map[string]int)
	for item, count := range a {
		if other, ok := b[item]; ok {
			out[item] = min(count, other)
		}
	}
	return out
}
for _, name := range names {
	fmt.Printf("%s: %d\n", name, shared[name])
}
for name := range shared {
	names = append(names, name)
}

Interactive Tools for This Topic

FAQ

How do you run Map Multiset Intersection Counts Overlap?
Just run the file; everything it needs ships with the runtime itself.