Programming Search⌘K

Taskcore

Use a custom key in a map

Also called user type as a map key, struct as a dictionary key, composite key, tuple key, hashable class.

Use a point type as the key of a map, with equality and a hash that agree, so that two equal points find one entry.

Task

Count points with a map whose key is a point. The function count_points(points) takes a list of points (x, y). It returns one triple (x, y, count) for each distinct point, where count is the number of times the point is in the list. The triples are in ascending order of x, then of y. For example, count_points([(1, 2), (3, 4), (1, 2)]) is [(1, 2, 2), (3, 4, 1)].

Each coordinate fits in a signed 32-bit integer. The list can be empty.

Solutions

Language Key type Equality and hash
Python @dataclass(frozen=True) class Point made from the fields
JavaScript, TypeScript the string "x,y" string equality
Java record Point(int x, int y) made from the fields
C# readonly record struct Point(int X, int Y) made from the fields
Go struct { X, Y int } == on each field; the map hashes the fields
Rust struct Point with #[derive(PartialEq, Eq, Hash)] made from the fields
C struct point in a sorted array a compare function
C++ struct Point with operator== and a hash type written by hand
Bash the string "x,y" string equality
  • Equality and hash together. A hash map first finds a bucket with the hash of the key, then compares the keys in it for equality. Thus two equal keys must have equal hashes. In Java, "If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result."1 In Rust, "When implementing both Hash and Eq, it is important that the following property holds: k1 == k2 -> hash(k1) == hash(k2)"2. Two unequal keys can have one hash. That makes the map slower, but not wrong.
  • Let the language make them. A record type gets equality and a hash from all of its fields, so the two agree. For a Java record, "The implicit declaration of the Object.equals(Object), Object.hashCode(), and Object.toString() methods are derived from all of the component fields."3 For a C# record, "two objects are equal if they are of the same type and store the same values."4 Rust keys must implement Eq and Hash, "although this can frequently be achieved by using #[derive(PartialEq, Eq, Hash)]."5 In Go, "Struct types are comparable if all their field types are comparable."6 Python dataclass(frozen=True) makes __eq__ and __hash__ from the fields.
  • Keys must not change. If a key changes while it is in a hash map, its hash changes, and the map looks in the wrong bucket. The frozen dataclass, the Java record and the readonly record struct have fields that cannot change. Another way is a tuple key, such as (x, y) in Python and Rust.
  • JavaScript and Bash. These languages have no hash for a user type. A JavaScript Map compares objects by identity, and a Bash associative array has string keys. Both solutions use the string "x,y" as the key. The comma is necessary: without it, (1, 23) and (12, 3) both give 123.
  • C++. std::unordered_map needs a hash type for a user key, and std::hash has no specialization for Point. The solution puts x and y in one 64-bit value and hashes it. A std::map needs only an order, for example std::tie(a.x, a.y) < std::tie(b.x, b.y).
  • C. C has no map type and no == for structs. The solution sorts the points with qsort, so that equal points are next to each other, then counts each run in one pass.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • swap: (1, 2) and (2, 1) are two points. A hash that adds x and y gives both the same hash, which is slow but correct.
  • empty: no points give no triples.
  • negative: negative coordinates sort before 0.
  • joined-digits: (1, 23) and (12, 3) are two points. A string key without a separator makes them one key.
  • all-same: three equal points give one triple with the count 3.

Pitfalls

  • Python __eq__ without __hash__ makes a class unhashable. "A class that overrides eq() and does not define hash() will have its hash() implicitly set to None."7 Then instances "will raise an appropriate TypeError when a program attempts to retrieve their hash value"7. Define __hash__ from the same fields as __eq__:
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __eq__(self, other):
        return (self.x, self.y) == (other.x, other.y)


class Fixed(Point):
    def __hash__(self):
        return hash((self.x, self.y))


try:
    counts = {Point(1, 2): 1}
except TypeError as e:
    print(type(e).__name__)
print({Fixed(1, 2): 1}[Fixed(1, 2)])
Output
TypeError
1
  • JavaScript a Map compares object keys by identity. "for object keys, equality is based on object identity."8 Two object literals with the same fields are two keys, so a read with a new object finds nothing. Use a string key:
const counts = new Map();
counts.set({ x: 1, y: 2 }, 1);
console.log(counts.get({ x: 1, y: 2 }));
counts.set("1,2", 1);
console.log(counts.get("1,2"));
Output
undefined
1
  • Java equals without hashCode loses keys. The class below overrides equals but keeps the hashCode of Object, so two equal points have two hashes, and HashMap looks in the wrong bucket. A record gets both from its fields3:
import java.util.HashMap;
import java.util.Map;

public class Main {
  static final class Point {
    final int x;
    final int y;

    Point(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public boolean equals(Object o) {
      return o instanceof Point p && p.x == x && p.y == y;
    }
  }

  record Fixed(int x, int y) {}

  public static void main(String[] args) {
    Map<Point, Integer> a = new HashMap<>();
    a.put(new Point(1, 2), 1);
    System.out.println(a.get(new Point(1, 2)));
    Map<Fixed, Integer> b = new HashMap<>();
    b.put(new Fixed(1, 2), 1);
    System.out.println(b.get(new Fixed(1, 2)));
  }
}
Output
null
1
  • C# a key that changes is lost. Override GetHashCode for a mutable type only if "You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code. Otherwise, you might think that the mutable object is lost in the hash table."9 Below, the key changes after the Add. The dictionary still has 1 entry, but no point finds it:
using System;
using System.Collections.Generic;

var p = new Point { X = 1, Y = 2 };
var counts = new Dictionary<Point, int> { [p] = 1 };
p.X = 5;
Console.WriteLine(counts.ContainsKey(p) + " " + counts.ContainsKey(new Point { X = 1, Y = 2 }));
Console.WriteLine(counts.Count);

class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public override bool Equals(object? obj) => obj is Point q && q.X == X && q.Y == Y;

    public override int GetHashCode() => HashCode.Combine(X, Y);
}
Output
False False
1
  • Go a pointer field compares the address. "Two pointer values are equal if they point to the same variable or if both have value nil."6 A struct key with a pointer field is equal to another key only if both point to one variable, not if the two values are equal. Use the value as the field:
package main

import "fmt"

type Key struct {
	name *string
}

func main() {
	a, b := "ann", "ann"
	counts := map[Key]int{}
	counts[Key{&a}]++
	counts[Key{&b}]++
	fmt.Println(len(counts))
	byName := map[string]int{}
	byName[a]++
	byName[b]++
	fmt.Println(len(byName))
}
Output
2
1
  • Rust derive uses all of the fields. The derived PartialEq and Hash agree, but they use each field. If two points with different labels must be one key, the label must not be in the key. Use a key type with only x and y, or write PartialEq and Hash by hand from the same fields:
use std::collections::HashMap;

#[derive(PartialEq, Eq, Hash)]
struct Place {
    x: i32,
    y: i32,
    label: &'static str,
}

fn main() {
    let mut counts = HashMap::new();
    *counts.entry(Place { x: 1, y: 2, label: "home" }).or_insert(0) += 1;
    *counts.entry(Place { x: 1, y: 2, label: "work" }).or_insert(0) += 1;
    println!("{}", counts.len());
    let mut by_point: HashMap<(i32, i32), i32> = HashMap::new();
    *by_point.entry((1, 2)).or_insert(0) += 1;
    *by_point.entry((1, 2)).or_insert(0) += 1;
    println!("{}", by_point.len());
}
Output
2
1
  • C++ a std::map order that skips a field joins keys. A std::map has no ==. Two keys are equivalent "if neither compares less than the other"10, that is, if !comp(a, b) && !comp(b, a). An order on x only makes (1, 2) and (1, 5) one key, and the map keeps the first key:
#include <iostream>
#include <map>

struct Point {
    int x;
    int y;
};

struct ByX {
    bool operator()(const Point &a, const Point &b) const { return a.x < b.x; }
};

struct ByXY {
    bool operator()(const Point &a, const Point &b) const {
        return a.x != b.x ? a.x < b.x : a.y < b.y;
    }
};

int main() {
    std::map<Point, int, ByX> a;
    a[{1, 2}]++;
    a[{1, 5}]++;
    std::cout << a.size() << ' ' << a.begin()->first.y << ' ' << a.begin()->second << '\n';
    std::map<Point, int, ByXY> b;
    b[{1, 2}]++;
    b[{1, 5}]++;
    std::cout << b.size() << '\n';
}
Output
1 2 2
2
  • C a string key needs a separator. A C program that keeps keys as text, for example for hsearch, often joins the fields with snprintf. strcmp "Compares two null-terminated byte strings lexicographically."11 It sees only the text, so the joined keys of (1, 23) and (12, 3) are equal. Put a separator between the fields:
#include <stdio.h>
#include <string.h>

int main(void) {
    char a[32];
    char b[32];
    snprintf(a, sizeof a, "%d%d", 1, 23);
    snprintf(b, sizeof b, "%d%d", 12, 3);
    printf("%s %s %d\n", a, b, strcmp(a, b) == 0);
    snprintf(a, sizeof a, "%d,%d", 1, 23);
    snprintf(b, sizeof b, "%d,%d", 12, 3);
    printf("%s %s %d\n", a, b, strcmp(a, b) == 0);
    return 0;
}
Output
123 123 1
1,23 12,3 0
  • Bash keys compare as text. Indexed arrays use numbers, but "associative arrays use arbitrary strings."12 Thus 1,2 and 01,2 are two keys, though they are one point. Put each coordinate in one form before you make the key. 10# reads a number in base 10, so a leading 0 does not make it octal:
declare -A seen=()
for p in 1,2 01,2 1,2; do
  seen[$p]=1
done
echo "${#seen[@]}"
seen=()
for p in 1,2 01,2 1,2; do
  x=${p%%,*} y=${p#*,}
  seen[$((10#$x)),$((10#$y))]=1
done
echo "${#seen[@]}"
Output
2
1

Code

The build runs the native tests of each language in a pinned toolchain.

count_points.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

from collections import Counter
from dataclasses import dataclass


# frozen=True makes the fields read-only and gives the class a __hash__ that
# agrees with its __eq__. order=True gives the order of x, then y.
@dataclass(frozen=True, order=True)
class Point:
    x: int
    y: int


def count_points(points: list[tuple[int, int]]) -> list[tuple[int, int, int]]:
    """Return (x, y, count) for each distinct point, in order of x, then y."""
    counts = Counter(Point(x, y) for x, y in points)
    return [(p.x, p.y, n) for p, n in sorted(counts.items())]
test_count_points.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

import pytest

from count_points import Point, count_points

CASES = {
    "clicks": ([(1, 2), (3, 4), (1, 2)], [(1, 2, 2), (3, 4, 1)]),
    "swap": ([(2, 1), (1, 2)], [(1, 2, 1), (2, 1, 1)]),
    "empty": ([], []),
    "one": ([(0, 0)], [(0, 0, 1)]),
    "negative": ([(-1, 0), (0, -1), (-1, 0)], [(-1, 0, 2), (0, -1, 1)]),
    "joined-digits": ([(1, 23), (12, 3)], [(1, 23, 1), (12, 3, 1)]),
    "all-same": ([(5, 5), (5, 5), (5, 5)], [(5, 5, 3)]),
}


@pytest.mark.parametrize("name", CASES)
def test_count_points(name):
    points, want = CASES[name]
    assert count_points(points) == want


def test_equal_points_have_equal_hashes():
    assert Point(1, 2) == Point(1, 2)
    assert hash(Point(1, 2)) == hash(Point(1, 2))
count_points.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#include "count_points.hpp"

#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <unordered_map>

namespace {

// Point is a map key. std::unordered_map needs == and a hash, and equal
// points must have equal hashes.
struct Point {
    int x;
    int y;
    bool operator==(const Point &) const = default;
};

struct PointHash {
    std::size_t operator()(const Point &p) const noexcept {
        // Put the two 32-bit values in one 64-bit value, then hash it.
        std::uint64_t bits = static_cast<std::uint64_t>(static_cast<std::uint32_t>(p.x)) << 32 | static_cast<std::uint32_t>(p.y);
        return std::hash<std::uint64_t>{}(bits);
    }
};

}  // namespace

std::vector<std::tuple<int, int, int>> count_points(const std::vector<std::pair<int, int>> &points) {
    std::unordered_map<Point, int, PointHash> counts;
    for (const auto &[x, y] : points) {
        counts[Point{x, y}]++;
    }
    std::vector<std::tuple<int, int, int>> out;
    out.reserve(counts.size());
    for (const auto &[p, n] : counts) {
        out.emplace_back(p.x, p.y, n);
    }
    std::ranges::sort(out);
    return out;
}
count_points.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#pragma once

#include <tuple>
#include <utility>
#include <vector>

// count_points returns (x, y, count) for each distinct point, in order of x,
// then y.
std::vector<std::tuple<int, int, int>> count_points(const std::vector<std::pair<int, int>> &points);
test_count_points.cpp 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#include "count_points.hpp"

#include <iostream>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>

static int failures = 0;

using Points = std::vector<std::pair<int, int>>;
using Triples = std::vector<std::tuple<int, int, int>>;

static void check(std::string_view name, const Points &points, const Triples &want) {
    if (count_points(points) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("clicks", Points{{1, 2}, {3, 4}, {1, 2}}, Triples{{1, 2, 2}, {3, 4, 1}});
    check("swap", Points{{2, 1}, {1, 2}}, Triples{{1, 2, 1}, {2, 1, 1}});
    check("empty", Points{}, Triples{});
    check("one", Points{{0, 0}}, Triples{{0, 0, 1}});
    check("negative", Points{{-1, 0}, {0, -1}, {-1, 0}}, Triples{{-1, 0, 2}, {0, -1, 1}});
    check("joined-digits", Points{{1, 23}, {12, 3}}, Triples{{1, 23, 1}, {12, 3, 1}});
    check("all-same", Points{{5, 5}, {5, 5}, {5, 5}}, Triples{{5, 5, 3}});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
CountPoints.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

final class CountPoints {
  private CountPoints() {}

  /** A record gets equals and hashCode from its fields, so it works as a map key. */
  record Point(int x, int y) {}

  /** Returns [x, y, count] for each distinct point, in order of x, then y. */
  static List<List<Integer>> countPoints(List<List<Integer>> points) {
    Map<Point, Integer> counts = new HashMap<>();
    for (List<Integer> p : points) {
      counts.merge(new Point(p.get(0), p.get(1)), 1, Integer::sum);
    }
    Comparator<Point> order = Comparator.comparingInt(Point::x).thenComparingInt(Point::y);
    return counts.entrySet().stream()
        .sorted(Map.Entry.comparingByKey(order))
        .map(e -> List.of(e.getKey().x(), e.getKey().y(), e.getValue()))
        .toList();
  }
}
CountPointsTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class CountPointsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("clicks", List.of(List.of(1, 2), List.of(3, 4), List.of(1, 2)), List.of(List.of(1, 2, 2), List.of(3, 4, 1))),
        Arguments.of("swap", List.of(List.of(2, 1), List.of(1, 2)), List.of(List.of(1, 2, 1), List.of(2, 1, 1))),
        Arguments.of("empty", List.of(), List.of()),
        Arguments.of("one", List.of(List.of(0, 0)), List.of(List.of(0, 0, 1))),
        Arguments.of("negative", List.of(List.of(-1, 0), List.of(0, -1), List.of(-1, 0)), List.of(List.of(-1, 0, 2), List.of(0, -1, 1))),
        Arguments.of("joined-digits", List.of(List.of(1, 23), List.of(12, 3)), List.of(List.of(1, 23, 1), List.of(12, 3, 1))),
        Arguments.of("all-same", List.of(List.of(5, 5), List.of(5, 5), List.of(5, 5)), List.of(List.of(5, 5, 3))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void countPoints(String name, List<List<Integer>> points, List<List<Integer>> want) {
    assertEquals(want, CountPoints.countPoints(points));
  }

  @Test
  void equalPointsHaveEqualHashCodes() {
    assertEquals(new CountPoints.Point(1, 2), new CountPoints.Point(1, 2));
    assertEquals(new CountPoints.Point(1, 2).hashCode(), new CountPoints.Point(1, 2).hashCode());
  }
}
count_points.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#include "count_points.h"

#include <stdbool.h>
#include <stdlib.h>

// cmp orders points by x, then y. It compares the values, because a - b can
// overflow an int.
static int cmp(const void *a, const void *b) {
    const struct point *p = a;
    const struct point *q = b;
    if (p->x != q->x) {
        return (p->x > q->x) - (p->x < q->x);
    }
    return (p->y > q->y) - (p->y < q->y);
}

// equal compares the fields. C has no == for structs, and memcmp would also
// compare the padding bytes of a struct that has them.
static bool equal(struct point a, struct point b) {
    return a.x == b.x && a.y == b.y;
}

size_t count_points(struct point *points, size_t n, struct point_count *out) {
    // C has no map type. After a sort, equal points are next to each other,
    // so one pass counts them.
    if (n > 0) {
        qsort(points, n, sizeof points[0], cmp);
    }
    size_t k = 0;
    for (size_t i = 0; i < n; i++) {
        if (k > 0 && equal(out[k - 1].p, points[i])) {
            out[k - 1].n++;
        } else {
            out[k++] = (struct point_count){points[i], 1};
        }
    }
    return k;
}
count_points.h 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#ifndef COUNT_POINTS_H
#define COUNT_POINTS_H

#include <stddef.h>

struct point {
    int x;
    int y;
};

struct point_count {
    struct point p;
    size_t n;
};

// count_points sorts the n points in place in order of x, then y. Then it
// writes one entry for each distinct point to out, in that order. out must
// have room for n entries. It returns the number of entries.
size_t count_points(struct point *points, size_t n, struct point_count *out);

#endif
test_count_points.c 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

#include "count_points.h"

#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// An empty array has a dummy item in it, because C has no empty array. The
// counts give the real lengths.
#define CHECK(name, cnt, pts, kk, ...)                                         \
    do {                                                                       \
        struct point points[] = pts;                                           \
        const struct point_count want[] = {__VA_ARGS__};                       \
        struct point_count out[sizeof points / sizeof points[0]];              \
        const size_t want_k = kk;                                              \
        size_t got = count_points(points, cnt, out);                           \
        int ok = got == want_k;                                                \
        for (size_t i = 0; ok && i < want_k; i++) {                            \
            ok = out[i].p.x == want[i].p.x && out[i].p.y == want[i].p.y &&     \
                 out[i].n == want[i].n;                                        \
        }                                                                      \
        if (!ok) {                                                             \
            fprintf(stderr, "case %s failed\n", name);                         \
            failures++;                                                        \
        }                                                                      \
    } while (0)

int main(void) {
    CHECK("clicks", 3, L({1, 2}, {3, 4}, {1, 2}), 2, {{1, 2}, 2}, {{3, 4}, 1});
    CHECK("swap", 2, L({2, 1}, {1, 2}), 2, {{1, 2}, 1}, {{2, 1}, 1});
    CHECK("empty", 0, L({0, 0}), 0, {{0, 0}, 0});
    CHECK("one", 1, L({0, 0}), 1, {{0, 0}, 1});
    CHECK("negative", 3, L({-1, 0}, {0, -1}, {-1, 0}), 2, {{-1, 0}, 2}, {{0, -1}, 1});
    CHECK("joined-digits", 2, L({1, 23}, {12, 3}), 2, {{1, 23}, 1}, {{12, 3}, 1});
    CHECK("all-same", 3, L({5, 5}, {5, 5}, {5, 5}), 1, {{5, 5}, 3});
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
CountPoints.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

using System.Collections.Generic;
using System.Linq;

// A record struct gets Equals and GetHashCode from its fields, and readonly
// keeps a key from a change while it is in a dictionary.
public readonly record struct Point(int X, int Y);

public static class CountPoints
{
    // Count returns (x, y, count) for each distinct point, in order of x, then y.
    public static (int X, int Y, int Count)[] Count(IEnumerable<Point> points)
    {
        var counts = new Dictionary<Point, int>();
        foreach (var p in points)
        {
            counts[p] = counts.GetValueOrDefault(p) + 1;
        }
        return counts.OrderBy(e => e.Key.X).ThenBy(e => e.Key.Y).Select(e => (e.Key.X, e.Key.Y, e.Value)).ToArray();
    }
}
CountPointsTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

using System.Linq;
using Xunit;

public sealed class CountPointsTests
{
    public static TheoryData<string, int[], int[], int[], int[], int[]> Cases => new()
    {
        { "clicks", new int[] { 1, 3, 1 }, new int[] { 2, 4, 2 }, new int[] { 1, 3 }, new int[] { 2, 4 }, new int[] { 2, 1 } },
        { "swap", new int[] { 2, 1 }, new int[] { 1, 2 }, new int[] { 1, 2 }, new int[] { 2, 1 }, new int[] { 1, 1 } },
        { "empty", new int[0], new int[0], new int[0], new int[0], new int[0] },
        { "one", new int[] { 0 }, new int[] { 0 }, new int[] { 0 }, new int[] { 0 }, new int[] { 1 } },
        { "negative", new int[] { -1, 0, -1 }, new int[] { 0, -1, 0 }, new int[] { -1, 0 }, new int[] { 0, -1 }, new int[] { 2, 1 } },
        { "joined-digits", new int[] { 1, 12 }, new int[] { 23, 3 }, new int[] { 1, 12 }, new int[] { 23, 3 }, new int[] { 1, 1 } },
        { "all-same", new int[] { 5, 5, 5 }, new int[] { 5, 5, 5 }, new int[] { 5 }, new int[] { 5 }, new int[] { 3 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] xs, int[] ys, int[] wantX, int[] wantY, int[] wantCount)
    {
        Assert.NotNull(name);
        var got = CountPoints.Count(xs.Zip(ys, (x, y) => new Point(x, y)));
        Assert.Equal(wantX, got.Select(t => t.X));
        Assert.Equal(wantY, got.Select(t => t.Y));
        Assert.Equal(wantCount, got.Select(t => t.Count));
    }

    [Fact]
    public void EqualPointsHaveEqualHashCodes()
    {
        Assert.Equal(new Point(1, 2), new Point(1, 2));
        Assert.Equal(new Point(1, 2).GetHashCode(), new Point(1, 2).GetHashCode());
    }
}
count_points.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

/**
 * @param {[number, number][]} points
 * @returns {[number, number, number][]}
 */
export function countPoints(points) {
  // A Map compares object keys by identity, so two arrays for one point would
  // be two keys. A string with a separator gives one key for each point.
  const counts = new Map();
  for (const [x, y] of points) {
    const key = `${x},${y}`;
    const entry = counts.get(key);
    if (entry === undefined) {
      counts.set(key, [x, y, 1]);
    } else {
      entry[2]++;
    }
  }
  return [...counts.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
}
count_points.test.js 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { countPoints } from "./count_points.js";

const cases = [
  ["clicks", [[1, 2], [3, 4], [1, 2]], [[1, 2, 2], [3, 4, 1]]],
  ["swap", [[2, 1], [1, 2]], [[1, 2, 1], [2, 1, 1]]],
  ["empty", [], []],
  ["one", [[0, 0]], [[0, 0, 1]]],
  ["negative", [[-1, 0], [0, -1], [-1, 0]], [[-1, 0, 2], [0, -1, 1]]],
  ["joined-digits", [[1, 23], [12, 3]], [[1, 23, 1], [12, 3, 1]]],
  ["all-same", [[5, 5], [5, 5], [5, 5]], [[5, 5, 3]]],
];

for (const [name, points, want] of cases) {
  test(name, () => {
    assert.deepEqual(countPoints(points), want);
  });
}
count_points.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

export function countPoints(points: readonly (readonly [number, number])[]): [number, number, number][] {
  // A Map compares object keys by identity, so two arrays for one point would
  // be two keys. A string with a separator gives one key for each point.
  const counts = new Map<string, [number, number, number]>();
  for (const [x, y] of points) {
    const key = `${x},${y}`;
    const entry = counts.get(key);
    if (entry === undefined) {
      counts.set(key, [x, y, 1]);
    } else {
      entry[2]++;
    }
  }
  return [...counts.values()].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
}
count_points.test.ts 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { countPoints } from "./count_points.ts";

const cases: [string, [number, number][], [number, number, number][]][] = [
  ["clicks", [[1, 2], [3, 4], [1, 2]], [[1, 2, 2], [3, 4, 1]]],
  ["swap", [[2, 1], [1, 2]], [[1, 2, 1], [2, 1, 1]]],
  ["empty", [], []],
  ["one", [[0, 0]], [[0, 0, 1]]],
  ["negative", [[-1, 0], [0, -1], [-1, 0]], [[-1, 0, 2], [0, -1, 1]]],
  ["joined-digits", [[1, 23], [12, 3]], [[1, 23, 1], [12, 3, 1]]],
  ["all-same", [[5, 5], [5, 5], [5, 5]], [[5, 5, 3]]],
];

for (const [name, points, want] of cases) {
  test(name, () => {
    assert.deepEqual(countPoints(points), want);
  });
}
count_points.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

// Package countpoints counts points with a map whose key is a struct.
package countpoints

import (
	"cmp"
	"slices"
)

// Point is a map key. A struct of comparable fields is comparable, and two
// values are equal if their fields are equal.
type Point struct {
	X, Y int
}

// Count is a point and the number of times it is in the input.
type Count struct {
	P Point
	N int
}

// CountPoints returns one Count for each distinct point, in order of X, then Y.
func CountPoints(points []Point) []Count {
	counts := make(map[Point]int)
	for _, p := range points {
		counts[p]++
	}
	out := make([]Count, 0, len(counts))
	for p, n := range counts {
		out = append(out, Count{p, n})
	}
	slices.SortFunc(out, func(a, b Count) int {
		return cmp.Or(cmp.Compare(a.P.X, b.P.X), cmp.Compare(a.P.Y, b.P.Y))
	})
	return out
}
count_points_test.go 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

package countpoints

import (
	"slices"
	"testing"
)

var cases = []struct {
	name   string
	points []Point
	want   []Count
}{
	{"clicks", []Point{{1, 2}, {3, 4}, {1, 2}}, []Count{{Point{1, 2}, 2}, {Point{3, 4}, 1}}},
	{"swap", []Point{{2, 1}, {1, 2}}, []Count{{Point{1, 2}, 1}, {Point{2, 1}, 1}}},
	{"empty", []Point{}, []Count{}},
	{"one", []Point{{0, 0}}, []Count{{Point{0, 0}, 1}}},
	{"negative", []Point{{-1, 0}, {0, -1}, {-1, 0}}, []Count{{Point{-1, 0}, 2}, {Point{0, -1}, 1}}},
	{"joined-digits", []Point{{1, 23}, {12, 3}}, []Count{{Point{1, 23}, 1}, {Point{12, 3}, 1}}},
	{"all-same", []Point{{5, 5}, {5, 5}, {5, 5}}, []Count{{Point{5, 5}, 3}}},
}

func TestCountPoints(t *testing.T) {
	for _, c := range cases {
		if got := CountPoints(c.points); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
count_points.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

use std::collections::HashMap;

/// A map key. The derived Hash and Eq use the same fields, so equal points
/// have equal hashes. The derived Ord gives the order of x, then y.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Point {
    pub x: i32,
    pub y: i32,
}

/// Returns (x, y, count) for each distinct point, in order of x, then y.
pub fn count_points(points: &[(i32, i32)]) -> Vec<(i32, i32, usize)> {
    let mut counts: HashMap<Point, usize> = HashMap::new();
    for &(x, y) in points {
        *counts.entry(Point { x, y }).or_insert(0) += 1;
    }
    let mut out: Vec<(Point, usize)> = counts.into_iter().collect();
    out.sort();
    out.into_iter().map(|(p, n)| (p.x, p.y, n)).collect()
}
tests/count_points_test.rs 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

use algo_use_a_custom_key_in_a_map::count_points;

#[test]
fn cases() {
    let cases: Vec<(&str, Vec<(i32, i32)>, Vec<(i32, i32, usize)>)> = vec![
        ("clicks", vec![(1, 2), (3, 4), (1, 2)], vec![(1, 2, 2), (3, 4, 1)]),
        ("swap", vec![(2, 1), (1, 2)], vec![(1, 2, 1), (2, 1, 1)]),
        ("empty", vec![], vec![]),
        ("one", vec![(0, 0)], vec![(0, 0, 1)]),
        ("negative", vec![(-1, 0), (0, -1), (-1, 0)], vec![(-1, 0, 2), (0, -1, 1)]),
        ("joined-digits", vec![(1, 23), (12, 3)], vec![(1, 23, 1), (12, 3, 1)]),
        ("all-same", vec![(5, 5), (5, 5), (5, 5)], vec![(5, 5, 3)]),
    ];
    for (name, points, want) in cases {
        assert_eq!(count_points(&points), want, "{name}");
    }
}
count_points.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

# count_points X,Y...
# Prints one line "X Y COUNT" for each distinct point, in ascending order of
# X, then Y.
count_points() {
  # Bash has no record type, so the key is the text "X,Y". The comma keeps
  # 1,23 and 12,3 apart. The keys compare as text, so the points must be in
  # one form: 1,2 and 01,2 would be two keys.
  local -A counts=()
  local p
  for p in "$@"; do
    counts[$p]=$(( ${counts[$p]-0} + 1 ))
  done
  for p in "${!counts[@]}"; do
    printf '%s %s %s\n' "${p%%,*}" "${p#*,}" "${counts[$p]}"
  done | LC_ALL=C sort -k1,1n -k2,2n
}
test_count_points.bats 27 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-custom-key-in-a-map/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/count_points.sh"
}

check() { # check WANT ARG...
  local want got
  # %b turns each \n in WANT into a newline. The x keeps the trailing
  # newlines, which $(...) removes.
  want=$(printf '%b' "$1"; printf x)
  shift
  got=$(count_points "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "clicks" { check "1 2 2\n3 4 1\n" 1,2 3,4 1,2; }
@test "swap" { check "1 2 1\n2 1 1\n" 2,1 1,2; }
@test "empty" { check ""; }
@test "one" { check "0 0 1\n" 0,0; }
@test "negative" { check "-1 0 2\n0 -1 1\n" -1,0 0,-1 -1,0; }
@test "joined-digits" { check "1 23 1\n12 3 1\n" 1,23 12,3; }
@test "all-same" { check "5 5 3\n" 5,5 5,5 5,5; }

References

  1. Java SE 25 API, Class Object, hashCode()
  2. Rust standard library, trait Hash, Hash and Eq
  3. Java SE 25 API, Class Record, Class description
  4. C# reference, Records, Value equality
  5. Rust standard library, struct HashMap, Struct description
  6. The Go Programming Language Specification, Comparison operators; Map types
  7. The Python Language Reference, Data model, object.__hash__
  8. MDN Web Docs, Map, Key equality
  9. .NET API reference, Object.GetHashCode method, Notes to inheritors
  10. cppreference.com, std::map, Description
  11. cppreference.com, strcmp (C), Description
  12. Bash Reference Manual, 6.7 Arrays

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source