Serialize a pair as a key
Updated
Encoding a pair as one primitive is a composite: string '4,1', or 4*n+1 when the second component is in 0..n-1. The encoding must be injective. Two different pairs must not hash as the same key.
What to focus on
Concatenating without a delimiter ('12' for (1,2) and for (12)) collides. 4*n+1 needs a proven bound on the second value. Prefer a real pair type when the language has one.
Worked examples
bounded encode
a = [], n = 10, pair (4,1)- key = 4*10+1=41
Result: {41: …} uniquely (4,1)
delimited string
a = [], pair (4,1)- key "4,1"
Result: {"4,1": …}
concat bug
a = [], pairs (1,2) and (12) as "12"- same string
Result: collision — lost a pair
Try it
Write encodePair(u, v, n). u and v are the pair components. n is the bound for the second component (v is in 0..n-1). Return the integer encoding u*n+v. Do not concatenate without a delimiter. a = [], n = 10, pair (4,1) → {41: …} uniquely (4,1). a = [], pair (4,1) → {\"4,1\": …}. a = [], pairs (1,2) and (12) as \"12\" → collision — lost a pair.
pair components are non-negative integers. When using u*n+v, the second component is in 0..n-1.