-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtables.b
executable file
·123 lines (108 loc) · 2.29 KB
/
tables.b
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
implement Tables;
include "tables.m";
Table[T].new(nslots: int, nilval: T): ref Table[T]
{
if(nslots == 0)
nslots = 13;
return ref Table[T](array[nslots] of list of (int, T), nilval);
}
Table[T].add(t: self ref Table[T], id: int, x: T): int
{
slot := id % len t.items;
for(q := t.items[slot]; q != nil; q = tl q)
if((hd q).t0 == id)
return 0;
t.items[slot] = (id, x) :: t.items[slot];
return 1;
}
Table[T].del(t: self ref Table[T], id: int): int
{
slot := id % len t.items;
p: list of (int, T);
r := 0;
for(q := t.items[slot]; q != nil; q = tl q){
if((hd q).t0 == id){
p = joinip(p, tl q);
r = 1;
break;
}
p = hd q :: p;
}
t.items[slot] = p;
return r;
}
Table[T].find(t: self ref Table[T], id: int): T
{
for(p := t.items[id % len t.items]; p != nil; p = tl p)
if((hd p).t0 == id)
return (hd p).t1;
return t.nilval;
}
Table[T].all(t: self ref Table): list of T
{
p: list of T;
for(i := 0; i < len t.items; i++)
for(j := t.items[i]; j != nil; j = tl j)
p = (hd j).t1 :: p;
return p;
}
Strhash[T].new(nslots: int, nilval: T): ref Strhash[T]
{
if(nslots == 0)
nslots = 13;
return ref Strhash[T](array[nslots] of list of (string, T), nilval);
}
Strhash[T].add(t: self ref Strhash, id: string, x: T)
{
slot := hash(id, len t.items);
t.items[slot] = (id, x) :: t.items[slot];
}
Strhash[T].del(t: self ref Strhash, id: string)
{
slot := hash(id, len t.items);
p: list of (string, T);
for(q := t.items[slot]; q != nil; q = tl q)
if((hd q).t0 != id)
p = hd q :: p;
t.items[slot] = p;
}
Strhash[T].find(t: self ref Strhash, id: string): T
{
for(p := t.items[hash(id, len t.items)]; p != nil; p = tl p)
if((hd p).t0 == id)
return (hd p).t1;
return t.nilval;
}
Strhash[T].all(t: self ref Strhash): list of T
{
p: list of T;
for(i := 0; i < len t.items; i++)
for(j := t.items[i]; j != nil; j = tl j)
p = (hd j).t1 :: p;
return p;
}
hash(s: string, n: int): int
{
h := 0;
m := len s;
for(i:=0; i<m; i++){
h = 65599*h+s[i];
}
return (h & 16r7fffffff) % n;
}
rev[T](x: list of T): list of T
{
l: list of T;
for(; x != nil; x = tl x)
l = hd x :: l;
return l;
}
# join x to y, leaving result in arbitrary order.
joinip[T](x, y: list of (int, T)): list of (int, T)
{
if(len x > len y)
(x, y) = (y, x);
for(; x != nil; x = tl x)
y = hd x :: y;
return y;
}