Taskintro
Create a map
Also called create a dictionary, make a hash map, build a map, add and remove map entries, dict literal.
Put key and value pairs in a new map, so a later pair replaces the value of its key, delete some keys, and list the entries in key order.
- Evidence
- Code in 10 languages
Task
Create a map, then change it. The function build_map(pairs, remove) puts each pair (key, value) of pairs in a new, empty map, in input order. A later pair with the same key replaces the value of that key. Then the function deletes each key of remove from the map. A key in remove that is not in the map does nothing. The function returns the entries of the map as pairs (key, value), in ascending order of the key by its bytes. For example, build_map([("a", 1), ("b", 2), ("a", 7), ("c", 3)], ["b"]) is [("a", 7), ("c", 3)].
Each key has 1 or more ASCII letters. Each value fits in a signed 32-bit integer. Both lists can be empty, and both can repeat a key.
Solutions
| Language | Create | Add or replace | Delete |
|---|---|---|---|
| Python | {} or dict() |
table[key] = value |
table.pop(key, None) |
| JavaScript, TypeScript | new Map() |
map.set(key, value) |
map.delete(key) |
| Java | new HashMap<>() |
map.put(key, value) |
map.remove(key) |
| C# | new Dictionary<string, int>() |
map[key] = value |
map.Remove(key) |
| Go | make(map[string]int) |
m[key] = value |
delete(m, key) |
| Rust | HashMap::new() |
map.insert(key, value) |
map.remove(key) |
| C | a sorted array of entries | a binary search, then a change or a memmove |
a binary search, then a memmove |
| C++ | std::unordered_map<std::string, int> |
map.insert_or_assign(key, value) |
map.erase(key) |
| Bash | local -A map=() |
map[key]=value |
unset 'map[key]' |
- Create. Each solution starts with an empty map and adds the pairs one at a time. A literal is the other way to create a map when the entries are known. In Python, "Use a comma-separated list of key: value pairs within braces"1, for example
{'jack': 4098, 'sjoerd': 4127}. In Go, "For map literals, each element must have a key."2 A Go literal with the same constant key two times does not compile: "It is an error to specify multiple elements with the same field selector or constant key value."2 - Add or replace. One operation adds a new key and replaces the value of a key that is there. For the C# indexer, "If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary."3 For Rust
insert, "If the map did have this key present, the value is updated, and the old value is returned."4 For C++insert_or_assign, "If the key does not exist, inserts the new value as if by insert"5. - Delete. Each delete operation accepts a key that is not in the map. In Go, "If the map m is nil or the element m[k] does not exist, delete is a no-op."2 Python
popwith a default does not raise an error: "If key is in the dictionary, remove it and return its value, else return default."1 - The order of the result. A hash map does not keep its keys in order, so each solution sorts the entries by key at the end. The keys are ASCII, so a comparison of chars, code units or bytes gives the same order, and
Bcomes beforea. - C. The C standard library has no map. The solution keeps the entries in an array in key order, finds a key with a binary search, and moves the entries after it with
memmoveto add or delete an entry. - Bash. The function takes the pairs as
KEY=VALUEarguments, then--, then the keys to delete. It prints one lineKEY VALUEfor each entry, andLC_ALL=C sortputs the lines in byte order.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no pairs and no keys to delete give an empty map.replace:[("k", 1), ("k", 2), ("k", 3)]gives one entry,("k", 3).delete-absent: a delete ofz, which is not in the map, does nothing.delete-all: a delete of every key gives an empty map.delete-twice: a second delete of the same key does nothing.zero-value: the values 0 and -4 are values like any other, and stay in the map.case: the keysb,B,aandAare four different keys, in the orderA,B,a,b.
Pitfalls
- Python a read or a del of a missing key raises KeyError. For
d[key], the dict "Raises a KeyError if key is not in the map."1del d[key]does the same. Usegetto read andpop(key, None)to delete a key that can be missing:
table = {"apple": 3}
try:
print(table["pear"])
except KeyError as e:
print(type(e).__name__, e)
print(table.get("pear"), table.get("pear", 0))
print(table.pop("pear", None), table)
KeyError 'pear'
None 0
None {'apple': 3}
- JavaScript map[key] = value sets a property, not an entry. "Setting Object properties works for Map objects as well, and can cause considerable confusion."6 "The value of 'bla' is not stored in the Map for queries."6 The size stays 0 and
hasgives false. Usesetandget:
const wrong = new Map();
wrong["apple"] = 3;
console.log(wrong.size, wrong.has("apple"));
const map = new Map();
map.set("apple", 3);
console.log(map.size, map.has("apple"), map.get("apple"));
0 false
1 true 3
- Java Map.of gives a map that cannot change. "Keys and values cannot be added, removed, or updated. Calling any mutator method on the Map will always cause UnsupportedOperationException to be thrown."7 Also, "Duplicate keys passed to a static factory method result in IllegalArgumentException."7 Copy the entries to a
HashMapto change them:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> fixed = Map.of("apple", 3);
try {
fixed.put("pear", 5);
} catch (UnsupportedOperationException e) {
System.out.println(e.getClass().getSimpleName());
}
try {
Map.of("apple", 3, "apple", 4);
} catch (IllegalArgumentException e) {
System.out.println(e.getClass().getSimpleName());
}
Map<String, Integer> map = new HashMap<>(fixed);
map.put("pear", 5);
System.out.println(map.get("pear"));
}
}
UnsupportedOperationException
IllegalArgumentException
5
- C# a read of a missing key throws, and Add of a key that is there throws. "If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key."3 "In contrast, the Add method does not modify existing elements."3 It throws an
ArgumentException. UseTryGetValueto read and the indexer to add or replace:
using System;
using System.Collections.Generic;
var map = new Dictionary<string, int> { ["apple"] = 3 };
try
{
Console.WriteLine(map["pear"]);
}
catch (KeyNotFoundException e)
{
Console.WriteLine(e.GetType().Name);
}
try
{
map.Add("apple", 4);
}
catch (ArgumentException e)
{
Console.WriteLine(e.GetType().Name);
}
map["apple"] = 4;
Console.WriteLine(map.TryGetValue("pear", out var n) + " " + n + " " + map["apple"]);
KeyNotFoundException
ArgumentException
False 0 4
- Go an assignment to a nil map panics. The zero value of a map type is nil. "A nil map is equivalent to an empty map except that no elements may be added."2 A read and a delete work, but an assignment panics. Create the map with
makeor a literal:
package main
import "fmt"
func main() {
var m map[string]int
fmt.Println(m["apple"], len(m), m == nil)
delete(m, "apple")
defer func() {
fmt.Println("panic:", recover())
ok := make(map[string]int)
ok["apple"] = 3
fmt.Println(ok)
}()
m["apple"] = 3
}
0 0 true
panic: assignment to entry in nil map
map[apple:3]
- Rust map[&key] panics for a missing key. For the index operation, the docs say "Panics if the key is not present in the HashMap."4 Use
get, which gives anOption.insertalso gives anOption, the old value:
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
println!("{:?}", map.insert("apple", 3));
println!("{:?}", map.insert("apple", 4));
println!("{:?} {:?}", map.get("apple"), map.get("pear"));
println!("{}", map["apple"]);
}
None
Some(3)
Some(4) None
4
- C++ operator[] adds a key when it reads. It returns "a reference to the value that is mapped to a key equivalent to key or x respectively, performing an insertion if such key does not already exist."8 A read of a missing key adds the key with the value 0. Use
find,containsoratto read:
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> map{{"apple", 3}};
std::cout << map.contains("pear") << ' ' << map.size() << '\n';
int n = map["pear"];
std::cout << n << ' ' << map.contains("pear") << ' ' << map.size() << '\n';
}
0 1
0 1 2
- C hsearch ENTER does not replace a value. POSIX gives a hash table, but only one for each process, and no function that deletes one entry. The action ENTER acts "if it cannot be found in the table"9: "ENTER indicates that the item should be inserted in the table at an appropriate point."9 For a key that is there,
hsearchreturns the old entry and does not change it. Change thedataof the returned entry:
#define _XOPEN_SOURCE 700
#include <search.h>
#include <stdio.h>
int main(void) {
static int three = 3;
static int four = 4;
if (hcreate(8) == 0) {
return 1;
}
char key[] = "apple";
hsearch((ENTRY){key, &three}, ENTER);
ENTRY *e = hsearch((ENTRY){key, &four}, ENTER);
printf("%d\n", *(int *)e->data);
e->data = &four;
e = hsearch((ENTRY){key, NULL}, FIND);
printf("%d\n", *(int *)e->data);
hdestroy();
return 0;
}
3
4
- Bash an array without declare -A uses numbers as keys. "Indexed arrays are referenced using arithmetic expressions that must expand to an integer"10. In an arithmetic expression,
appleis the name of a variable, and "A shell variable that is null or unset evaluates to 0 when referenced by name in an expression."10 Thusappleandpearare both the index 0. "Associative arrays are created using declare -A name"10:
f() {
local wrong=()
wrong[apple]=3
wrong[pear]=5
echo "${#wrong[@]} ${!wrong[*]} ${wrong[0]}"
local -A map=()
map[apple]=3
map[pear]=5
echo "${#map[@]} ${map[apple]} ${map[pear]}"
}
f
1 0 5
2 3 5
Related tasks
- Iterate over a map: list the keys, the values and the entries of a map.
- Merge two maps: combine the entries of two maps.
- Use a map with a default value: read a missing key with a default value.
- Use a custom key in a map: use a value of your own type as a key.
- Create a set: a set is a map with keys and no values.
- Create an array: the same task for an array.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-map/.
def build_map(pairs: list[tuple[str, int]], remove: list[str]) -> list[tuple[str, int]]:
"""Put the pairs in a dict, delete the keys in remove, and return the entries sorted by key."""
table: dict[str, int] = {}
for key, value in pairs:
# An assignment adds the key, or replaces the value of a key that is there.
table[key] = value
for key in remove:
# pop with a default does not raise KeyError for a key that is not there.
table.pop(key, None)
return sorted(table.items())
test_build_map.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-map/.
import pytest
from build_map import build_map
CASES = {
"fruits": ([("apple", 3), ("pear", 5), ("fig", 2)], [], [("apple", 3), ("fig", 2), ("pear", 5)]),
"update-and-delete": ([("a", 1), ("b", 2), ("a", 7), ("c", 3)], ["b"], [("a", 7), ("c", 3)]),
"empty": ([], [], []),
"replace": ([("k", 1), ("k", 2), ("k", 3)], [], [("k", 3)]),
"delete-absent": ([("a", 1)], ["z"], [("a", 1)]),
"delete-all": ([("a", 1), ("b", 2)], ["a", "b"], []),
"delete-twice": ([("a", 1), ("b", 2)], ["a", "a"], [("b", 2)]),
"zero-value": ([("a", 0), ("b", -4)], [], [("a", 0), ("b", -4)]),
"case": ([("b", 1), ("B", 2), ("a", 3), ("A", 4)], [], [("A", 4), ("B", 2), ("a", 3), ("b", 1)]),
}
@pytest.mark.parametrize("name", CASES)
def test_build_map(name):
pairs, remove, want = CASES[name]
assert build_map(pairs, remove) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#include "build_map.hpp"
#include <algorithm>
#include <unordered_map>
std::vector<std::pair<std::string, int>> build_map(const std::vector<std::pair<std::string, int>> &pairs, const std::vector<std::string> &remove) {
std::unordered_map<std::string, int> map;
for (const auto &[key, value] : pairs) {
// insert_or_assign adds the key, or replaces the value of a key that is there.
map.insert_or_assign(key, value);
}
for (const auto &key : remove) {
// erase returns 0 for a key that is not there.
map.erase(key);
}
std::vector<std::pair<std::string, int>> out(map.begin(), map.end());
// std::string compares its chars, so the keys sort by their bytes.
std::sort(out.begin(), out.end());
return out;
}
build_map.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#pragma once
#include <string>
#include <utility>
#include <vector>
// build_map puts the pairs in a map, erases the keys in remove, and returns
// the entries in ascending order of the key.
std::vector<std::pair<std::string, int>> build_map(const std::vector<std::pair<std::string, int>> &pairs, const std::vector<std::string> &remove);
test_build_map.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#include "build_map.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
static int failures = 0;
using Pairs = std::vector<std::pair<std::string, int>>;
static void check(std::string_view name, const Pairs &pairs, const std::vector<std::string> &remove, const Pairs &want) {
if (build_map(pairs, remove) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("fruits", Pairs{{"apple", 3}, {"pear", 5}, {"fig", 2}}, std::vector<std::string>{}, Pairs{{"apple", 3}, {"fig", 2}, {"pear", 5}});
check("update-and-delete", Pairs{{"a", 1}, {"b", 2}, {"a", 7}, {"c", 3}}, std::vector<std::string>{"b"}, Pairs{{"a", 7}, {"c", 3}});
check("empty", Pairs{}, std::vector<std::string>{}, Pairs{});
check("replace", Pairs{{"k", 1}, {"k", 2}, {"k", 3}}, std::vector<std::string>{}, Pairs{{"k", 3}});
check("delete-absent", Pairs{{"a", 1}}, std::vector<std::string>{"z"}, Pairs{{"a", 1}});
check("delete-all", Pairs{{"a", 1}, {"b", 2}}, std::vector<std::string>{"a", "b"}, Pairs{});
check("delete-twice", Pairs{{"a", 1}, {"b", 2}}, std::vector<std::string>{"a", "a"}, Pairs{{"b", 2}});
check("zero-value", Pairs{{"a", 0}, {"b", -4}}, std::vector<std::string>{}, Pairs{{"a", 0}, {"b", -4}});
check("case", Pairs{{"b", 1}, {"B", 2}, {"a", 3}, {"A", 4}}, std::vector<std::string>{}, Pairs{{"A", 4}, {"B", 2}, {"a", 3}, {"b", 1}});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
final class BuildMap {
private BuildMap() {}
/** Puts the pairs in a map, removes the keys in remove, and returns the entries sorted by key. */
static List<Map.Entry<String, Integer>> buildMap(List<Map.Entry<String, Integer>> pairs, List<String> remove) {
Map<String, Integer> map = new HashMap<>();
for (var pair : pairs) {
// put adds the key, or replaces the value of a key that is there.
map.put(pair.getKey(), pair.getValue());
}
for (var key : remove) {
// remove returns null for a key that is not there.
map.remove(key);
}
// A TreeMap orders String keys by compareTo, which compares the chars.
return new TreeMap<>(map).entrySet().stream()
.map(e -> Map.entry(e.getKey(), e.getValue()))
.toList();
}
}
BuildMapTest.java 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class BuildMapTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("fruits", List.of(Map.entry("apple", 3), Map.entry("pear", 5), Map.entry("fig", 2)), List.of(), List.of(Map.entry("apple", 3), Map.entry("fig", 2), Map.entry("pear", 5))),
Arguments.of("update-and-delete", List.of(Map.entry("a", 1), Map.entry("b", 2), Map.entry("a", 7), Map.entry("c", 3)), List.of("b"), List.of(Map.entry("a", 7), Map.entry("c", 3))),
Arguments.of("empty", List.of(), List.of(), List.of()),
Arguments.of("replace", List.of(Map.entry("k", 1), Map.entry("k", 2), Map.entry("k", 3)), List.of(), List.of(Map.entry("k", 3))),
Arguments.of("delete-absent", List.of(Map.entry("a", 1)), List.of("z"), List.of(Map.entry("a", 1))),
Arguments.of("delete-all", List.of(Map.entry("a", 1), Map.entry("b", 2)), List.of("a", "b"), List.of()),
Arguments.of("delete-twice", List.of(Map.entry("a", 1), Map.entry("b", 2)), List.of("a", "a"), List.of(Map.entry("b", 2))),
Arguments.of("zero-value", List.of(Map.entry("a", 0), Map.entry("b", -4)), List.of(), List.of(Map.entry("a", 0), Map.entry("b", -4))),
Arguments.of("case", List.of(Map.entry("b", 1), Map.entry("B", 2), Map.entry("a", 3), Map.entry("A", 4)), List.of(), List.of(Map.entry("A", 4), Map.entry("B", 2), Map.entry("a", 3), Map.entry("b", 1))));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void buildMap(String name, List<Map.Entry<String, Integer>> pairs, List<String> remove, List<Map.Entry<String, Integer>> want) {
assertEquals(want, BuildMap.buildMap(pairs, remove));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#include "build_map.h"
#include <string.h>
// find returns the index of key in the sorted entries map[0 .. k), or the
// index where key goes. *found tells which.
static size_t find(const struct entry *map, size_t k, const char *key, int *found) {
size_t lo = 0;
size_t hi = k;
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
int c = strcmp(map[mid].key, key);
if (c == 0) {
*found = 1;
return mid;
}
if (c < 0) {
lo = mid + 1;
} else {
hi = mid;
}
}
*found = 0;
return lo;
}
size_t build_map(const struct entry *pairs, size_t n, const char *const *drop, size_t m, struct entry *out) {
// The map is a sorted array. C has no map type in its standard library.
size_t k = 0;
for (size_t i = 0; i < n; i++) {
int found;
size_t at = find(out, k, pairs[i].key, &found);
if (found) {
out[at].value = pairs[i].value;
continue;
}
memmove(&out[at + 1], &out[at], (k - at) * sizeof out[0]);
out[at] = pairs[i];
k++;
}
for (size_t i = 0; i < m; i++) {
int found;
size_t at = find(out, k, drop[i], &found);
if (found) {
memmove(&out[at], &out[at + 1], (k - at - 1) * sizeof out[0]);
k--;
}
}
return k;
}
build_map.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#ifndef BUILD_MAP_H
#define BUILD_MAP_H
#include <stddef.h>
// An entry of the map. The key points into the caller's strings.
struct entry {
const char *key;
int value;
};
// build_map puts the n pairs in a map, removes the m keys in drop, and
// writes the entries to out in ascending order of the key. out must have room
// for n entries. It returns the number of entries.
size_t build_map(const struct entry *pairs, size_t n, const char *const *drop, size_t m, struct entry *out);
#endif
test_build_map.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
#include "build_map.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list has a dummy item in it, because C has no empty array. The
// counts give the real lengths.
#define CHECK(name, n, given, m, del, k, ...) \
do { \
const struct entry g[] = given; \
const char *const d[] = del; \
const struct entry want[] = {__VA_ARGS__}; \
struct entry out[sizeof g / sizeof g[0]]; \
const size_t want_k = k; \
size_t got = build_map(g, n, d, m, out); \
int ok = got == want_k; \
for (size_t i = 0; ok && i < want_k; i++) { \
ok = strcmp(out[i].key, want[i].key) == 0 && \
out[i].value == want[i].value; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("fruits", 3, L({"apple", 3}, {"pear", 5}, {"fig", 2}), 0, L(""), 3, {"apple", 3}, {"fig", 2}, {"pear", 5});
CHECK("update-and-delete", 4, L({"a", 1}, {"b", 2}, {"a", 7}, {"c", 3}), 1, L("b"), 2, {"a", 7}, {"c", 3});
CHECK("empty", 0, L({"", 0}), 0, L(""), 0, {NULL, 0});
CHECK("replace", 3, L({"k", 1}, {"k", 2}, {"k", 3}), 0, L(""), 1, {"k", 3});
CHECK("delete-absent", 1, L({"a", 1}), 1, L("z"), 1, {"a", 1});
CHECK("delete-all", 2, L({"a", 1}, {"b", 2}), 2, L("a", "b"), 0, {NULL, 0});
CHECK("delete-twice", 2, L({"a", 1}, {"b", 2}), 2, L("a", "a"), 1, {"b", 2});
CHECK("zero-value", 2, L({"a", 0}, {"b", -4}), 0, L(""), 2, {"a", 0}, {"b", -4});
CHECK("case", 4, L({"b", 1}, {"B", 2}, {"a", 3}, {"A", 4}), 0, L(""), 4, {"A", 4}, {"B", 2}, {"a", 3}, {"b", 1});
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
using System;
using System.Collections.Generic;
using System.Linq;
public static class BuildMap
{
// Build puts the pairs in a dictionary, removes the keys in remove, and returns the entries sorted by key.
public static (string Key, int Value)[] Build((string Key, int Value)[] pairs, string[] remove)
{
var map = new Dictionary<string, int>();
foreach (var (key, value) in pairs)
{
// The indexer adds the key, or replaces the value of a key that is there. Add would throw.
map[key] = value;
}
foreach (var key in remove)
{
// Remove returns false for a key that is not there.
map.Remove(key);
}
// StringComparer.Ordinal compares the chars. The default comparer depends on the culture.
return map.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => (p.Key, p.Value)).ToArray();
}
}
BuildMapTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
using System.Linq;
using Xunit;
public sealed class BuildMapTests
{
public static TheoryData<string, string[], int[], string[], string[], int[]> Cases => new()
{
{ "fruits", new string[] { "apple", "pear", "fig" }, new int[] { 3, 5, 2 }, new string[0], new string[] { "apple", "fig", "pear" }, new int[] { 3, 2, 5 } },
{ "update-and-delete", new string[] { "a", "b", "a", "c" }, new int[] { 1, 2, 7, 3 }, new string[] { "b" }, new string[] { "a", "c" }, new int[] { 7, 3 } },
{ "empty", new string[0], new int[0], new string[0], new string[0], new int[0] },
{ "replace", new string[] { "k", "k", "k" }, new int[] { 1, 2, 3 }, new string[0], new string[] { "k" }, new int[] { 3 } },
{ "delete-absent", new string[] { "a" }, new int[] { 1 }, new string[] { "z" }, new string[] { "a" }, new int[] { 1 } },
{ "delete-all", new string[] { "a", "b" }, new int[] { 1, 2 }, new string[] { "a", "b" }, new string[0], new int[0] },
{ "delete-twice", new string[] { "a", "b" }, new int[] { 1, 2 }, new string[] { "a", "a" }, new string[] { "b" }, new int[] { 2 } },
{ "zero-value", new string[] { "a", "b" }, new int[] { 0, -4 }, new string[0], new string[] { "a", "b" }, new int[] { 0, -4 } },
{ "case", new string[] { "b", "B", "a", "A" }, new int[] { 1, 2, 3, 4 }, new string[0], new string[] { "A", "B", "a", "b" }, new int[] { 4, 2, 3, 1 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] keys, int[] values, string[] remove, string[] wantKeys, int[] wantValues)
{
Assert.NotNull(name);
var got = BuildMap.Build(keys.Zip(values).ToArray(), remove);
Assert.Equal(wantKeys, got.Select(p => p.Key));
Assert.Equal(wantValues, got.Select(p => p.Value));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
/**
* @param {[string, number][]} pairs
* @param {string[]} remove
* @returns {[string, number][]}
*/
export function buildMap(pairs, remove) {
const map = new Map();
for (const [key, value] of pairs) {
// set adds the key, or replaces the value of a key that is there.
map.set(key, value);
}
for (const key of remove) {
// delete returns false for a key that is not there.
map.delete(key);
}
// Compare the keys by their code units. localeCompare would put "a" before "B".
return [...map].sort((p, q) => (p[0] < q[0] ? -1 : p[0] > q[0] ? 1 : 0));
}
build_map.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { buildMap } from "./build_map.js";
const cases = [
["fruits", [["apple", 3], ["pear", 5], ["fig", 2]], [], [["apple", 3], ["fig", 2], ["pear", 5]]],
["update-and-delete", [["a", 1], ["b", 2], ["a", 7], ["c", 3]], ["b"], [["a", 7], ["c", 3]]],
["empty", [], [], []],
["replace", [["k", 1], ["k", 2], ["k", 3]], [], [["k", 3]]],
["delete-absent", [["a", 1]], ["z"], [["a", 1]]],
["delete-all", [["a", 1], ["b", 2]], ["a", "b"], []],
["delete-twice", [["a", 1], ["b", 2]], ["a", "a"], [["b", 2]]],
["zero-value", [["a", 0], ["b", -4]], [], [["a", 0], ["b", -4]]],
["case", [["b", 1], ["B", 2], ["a", 3], ["A", 4]], [], [["A", 4], ["B", 2], ["a", 3], ["b", 1]]],
];
for (const [name, pairs, remove, want] of cases) {
test(name, () => {
assert.deepEqual(buildMap(pairs, remove), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
export function buildMap(pairs: readonly [string, number][], remove: readonly string[]): [string, number][] {
const map = new Map<string, number>();
for (const [key, value] of pairs) {
// set adds the key, or replaces the value of a key that is there.
map.set(key, value);
}
for (const key of remove) {
// delete returns false for a key that is not there.
map.delete(key);
}
// Compare the keys by their code units. localeCompare would put "a" before "B".
return [...map].sort((p, q) => (p[0] < q[0] ? -1 : p[0] > q[0] ? 1 : 0));
}
build_map.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { buildMap } from "./build_map.ts";
const cases: [string, [string, number][], string[], [string, number][]][] = [
["fruits", [["apple", 3], ["pear", 5], ["fig", 2]], [], [["apple", 3], ["fig", 2], ["pear", 5]]],
["update-and-delete", [["a", 1], ["b", 2], ["a", 7], ["c", 3]], ["b"], [["a", 7], ["c", 3]]],
["empty", [], [], []],
["replace", [["k", 1], ["k", 2], ["k", 3]], [], [["k", 3]]],
["delete-absent", [["a", 1]], ["z"], [["a", 1]]],
["delete-all", [["a", 1], ["b", 2]], ["a", "b"], []],
["delete-twice", [["a", 1], ["b", 2]], ["a", "a"], [["b", 2]]],
["zero-value", [["a", 0], ["b", -4]], [], [["a", 0], ["b", -4]]],
["case", [["b", 1], ["B", 2], ["a", 3], ["A", 4]], [], [["A", 4], ["B", 2], ["a", 3], ["b", 1]]],
];
for (const [name, pairs, remove, want] of cases) {
test(name, () => {
assert.deepEqual(buildMap(pairs, remove), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
// Package buildmap creates a map, changes it and lists its entries.
package buildmap
import (
"maps"
"slices"
)
// Pair is one entry of the map.
type Pair struct {
Key string
Value int
}
// BuildMap puts the pairs in a map, deletes the keys in remove, and returns
// the entries in ascending order of the key.
func BuildMap(pairs []Pair, remove []string) []Pair {
// make gives an empty map. A nil map panics on an assignment.
m := make(map[string]int)
for _, p := range pairs {
// An assignment adds the key, or replaces the value of a key that is there.
m[p.Key] = p.Value
}
for _, k := range remove {
// delete does nothing for a key that is not there.
delete(m, k)
}
out := make([]Pair, 0, len(m))
for _, k := range slices.Sorted(maps.Keys(m)) {
out = append(out, Pair{k, m[k]})
}
return out
}
build_map_test.go 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
package buildmap
import (
"slices"
"testing"
)
var cases = []struct {
name string
pairs []Pair
remove []string
want []Pair
}{
{"fruits", []Pair{{"apple", 3}, {"pear", 5}, {"fig", 2}}, []string{}, []Pair{{"apple", 3}, {"fig", 2}, {"pear", 5}}},
{"update-and-delete", []Pair{{"a", 1}, {"b", 2}, {"a", 7}, {"c", 3}}, []string{"b"}, []Pair{{"a", 7}, {"c", 3}}},
{"empty", []Pair{}, []string{}, []Pair{}},
{"replace", []Pair{{"k", 1}, {"k", 2}, {"k", 3}}, []string{}, []Pair{{"k", 3}}},
{"delete-absent", []Pair{{"a", 1}}, []string{"z"}, []Pair{{"a", 1}}},
{"delete-all", []Pair{{"a", 1}, {"b", 2}}, []string{"a", "b"}, []Pair{}},
{"delete-twice", []Pair{{"a", 1}, {"b", 2}}, []string{"a", "a"}, []Pair{{"b", 2}}},
{"zero-value", []Pair{{"a", 0}, {"b", -4}}, []string{}, []Pair{{"a", 0}, {"b", -4}}},
{"case", []Pair{{"b", 1}, {"B", 2}, {"a", 3}, {"A", 4}}, []string{}, []Pair{{"A", 4}, {"B", 2}, {"a", 3}, {"b", 1}}},
}
func TestBuildMap(t *testing.T) {
for _, c := range cases {
if got := BuildMap(c.pairs, c.remove); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
use std::collections::HashMap;
/// Puts the pairs in a map, removes the keys in `remove`, and returns the entries sorted by key.
pub fn build_map<'a>(pairs: &[(&'a str, i32)], remove: &[&str]) -> Vec<(&'a str, i32)> {
let mut map: HashMap<&'a str, i32> = HashMap::new();
for &(key, value) in pairs {
// insert adds the key, or replaces the value and returns the old one.
map.insert(key, value);
}
for &key in remove {
// remove returns None for a key that is not there.
map.remove(key);
}
let mut out: Vec<(&'a str, i32)> = map.into_iter().collect();
// A str compares by its bytes.
out.sort();
out
}
tests/build_map_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/create-a-map/.
use algo_create_a_map::build_map;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<(&str, i32)>, Vec<&str>, Vec<(&str, i32)>)> = vec![
("fruits", vec![("apple", 3), ("pear", 5), ("fig", 2)], vec![], vec![("apple", 3), ("fig", 2), ("pear", 5)]),
("update-and-delete", vec![("a", 1), ("b", 2), ("a", 7), ("c", 3)], vec!["b"], vec![("a", 7), ("c", 3)]),
("empty", vec![], vec![], vec![]),
("replace", vec![("k", 1), ("k", 2), ("k", 3)], vec![], vec![("k", 3)]),
("delete-absent", vec![("a", 1)], vec!["z"], vec![("a", 1)]),
("delete-all", vec![("a", 1), ("b", 2)], vec!["a", "b"], vec![]),
("delete-twice", vec![("a", 1), ("b", 2)], vec!["a", "a"], vec![("b", 2)]),
("zero-value", vec![("a", 0), ("b", -4)], vec![], vec![("a", 0), ("b", -4)]),
("case", vec![("b", 1), ("B", 2), ("a", 3), ("A", 4)], vec![], vec![("A", 4), ("B", 2), ("a", 3), ("b", 1)]),
];
for (name, pairs, remove, want) in cases {
assert_eq!(build_map(&pairs, &remove), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-map/.
# build_map KEY=VALUE... [-- KEY...]
# Puts each KEY=VALUE pair in an associative array, so a later pair replaces
# the value of the key, then unsets each KEY after --. Prints one line
# "KEY VALUE" for each entry, in ascending order of the key by its bytes.
build_map() {
local -A map=()
local key
while (($# > 0)) && [[ $1 != -- ]]; do
map[${1%%=*}]=${1#*=}
shift
done
if (($# > 0)); then
shift
fi
for key in "$@"; do
# The quotes stop the shell from expanding the subscript as a glob.
unset 'map[$key]'
done
# LC_ALL=C makes sort compare bytes, so B comes before a.
for key in "${!map[@]}"; do
printf '%s %s\n' "$key" "${map[$key]}"
done | LC_ALL=C sort
}
test_build_map.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/create-a-map/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/build_map.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=$(build_map "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "fruits" { check "apple 3\nfig 2\npear 5\n" apple=3 pear=5 fig=2; }
@test "update-and-delete" { check "a 7\nc 3\n" a=1 b=2 a=7 c=3 -- b; }
@test "empty" { check ""; }
@test "replace" { check "k 3\n" k=1 k=2 k=3; }
@test "delete-absent" { check "a 1\n" a=1 -- z; }
@test "delete-all" { check "" a=1 b=2 -- a b; }
@test "delete-twice" { check "b 2\n" a=1 b=2 -- a a; }
@test "zero-value" { check "a 0\nb -4\n" a=0 b=-4; }
@test "case" { check "A 4\nB 2\na 3\nb 1\n" b=1 B=2 a=3 A=4; }
References
- The Python Standard Library, Built-in Types, Mapping Types, dict
- The Go Programming Language Specification, Composite literals; Map types; Deletion of map elements
- .NET API reference, Dictionary<TKey,TValue>.Item[TKey] property, Remarks
- Rust standard library, struct HashMap, insert; impl Index
- cppreference.com, std::unordered_map::insert_or_assign, Description
- MDN Web Docs, Map, Setting object properties
- Java SE 25 API, Interface Map, Unmodifiable Maps
- cppreference.com, std::unordered_map::operator[], Description
- POSIX.1-2024, hcreate, hdestroy, hsearch, DESCRIPTION
- Bash Reference Manual, 6.7 Arrays; 6.5 Shell Arithmetic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag VJ920A Edit this page History Report an error Markdown