-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMap.c
More file actions
128 lines (100 loc) · 2.67 KB
/
Map.c
File metadata and controls
128 lines (100 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
https://powcoder.com
代写代考加微信 powcoder
Assignment Project Exam Help
Add WeChat powcoder
// Implementation of the Map ADT
// !!! DO NOT MODIFY THIS FILE !!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Map.h"
#define DEFAULT_CAPACITY 8
struct map {
int size;
int capacity;
struct item *items;
};
struct item {
char *key;
int value;
};
static int ceilingIndex(Map m, char *key);
static void increaseCapacity(Map m);
Map MapNew(void) {
Map m = malloc(sizeof(*m));
if (m == NULL) {
fprintf(stderr, "Insufficient memory!\n");
exit(EXIT_FAILURE);
}
m->size = 0;
m->capacity = DEFAULT_CAPACITY;
m->items = malloc(m->capacity * sizeof(struct item));
if (m->items == NULL) {
fprintf(stderr, "error: out of memory\n");
exit(EXIT_FAILURE);
}
return m;
}
void MapFree(Map m) {
for (int i = 0; i < m->size; i++) {
free(m->items[i].key);
}
free(m->items);
free(m);
}
void MapSet(Map m, char *key, int value) {
int index = ceilingIndex(m, key);
if (index != -1 && strcmp(m->items[index].key, key) == 0) {
m->items[index].value = value;
return;
}
if (m->size == m->capacity) {
increaseCapacity(m);
}
int insertIndex = index == -1 ? m->size : index;
for (int i = m->size - 1; i >= insertIndex; i--) {
m->items[i + 1] = m->items[i];
}
m->items[insertIndex] = (struct item){strdup(key), value};
m->size++;
}
// Returns the index of the smallest key that is greater than or equal
// to the given key, or -1 if no such key exists
static int ceilingIndex(Map m, char *key) {
int index = -1;
int lo = 0;
int hi = m->size - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
int cmp = strcmp(key, m->items[mid].key);
if (cmp < 0) {
index = mid;
hi = mid - 1;
} else if (cmp > 0) {
lo = mid + 1;
} else {
return mid;
}
}
return index;
}
static void increaseCapacity(Map m) {
m->capacity *= 2;
m->items = realloc(m->items, m->capacity * sizeof(struct item));
if (m->items == NULL) {
fprintf(stderr, "error: out of memory\n");
exit(EXIT_FAILURE);
}
}
bool MapContains(Map m, char *key) {
int index = ceilingIndex(m, key);
return index != -1 && strcmp(m->items[index].key, key) == 0;
}
int MapGet(Map m, char *key) {
int index = ceilingIndex(m, key);
if (index == -1 || strcmp(m->items[index].key, key) != 0) {
fprintf(stderr, "error: key '%s' does not exist\n", key);
exit(EXIT_FAILURE);
}
return m->items[index].value;
}