-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathadjacency-matrix-unweighted-directed.ts
106 lines (88 loc) · 2.59 KB
/
adjacency-matrix-unweighted-directed.ts
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
import type {
AdjacencyStructure,
AdjacencyStructureConstructor,
Bit,
TypedArrayConstructors,
} from "./utility-types.ts";
import { getLog2 } from "./utilities.ts";
/**
* Implements the Adjacency Matrix structure for unweighted directed graphs.
*/
export class AdjacencyMatrixUnweightedDirected extends Uint32Array
implements AdjacencyStructure {
static directed = true;
static weighted = false;
empty = 0;
static get [Symbol.species](): Uint32ArrayConstructor {
return Uint32Array;
}
_size = 0;
get size() {
return this._size || ((this._size = getLog2(this.vertices)), this._size);
}
get vertices() {
return this[this.length - 1];
}
set vertices(value: number) {
this[this.length - 1] = value;
this._size = getLog2(value);
}
get edges() {
return this.vertices ** 2;
}
static create<
T extends AdjacencyStructureConstructor<TypedArrayConstructors>,
>(this: T, vertices: number): InstanceType<T> {
const length = this.getLength(vertices);
const matrix = new this(length);
matrix.vertices = vertices;
return matrix as InstanceType<T>;
}
static getLength(vertices: number) {
return ((vertices << getLog2(vertices)) >> 5) + 2;
}
addEdge(x: number, y: number): this {
const [bucket, position] = this.getCoordinates(x, y);
if (Number.isNaN(bucket)) return this;
this[bucket] = (this[bucket] & ~(1 << position)) | (1 << position);
return this;
}
getCoordinates(x: number, y = 1): [bucket: number, position: number] {
const index = this.getIndex(x, y);
const bucket = index >> 5;
if (bucket >= this.length - 1) return [NaN, NaN];
return [bucket, index - (bucket << 5)];
}
getEdge(x: number, y: number): number {
const [bucket, position] = this.getCoordinates(x, y);
if (Number.isNaN(bucket)) return 0;
return ((this[bucket] >> position) & 1) as Bit;
}
getIndex(x: number, y: number): number {
return (x << this.size) + y;
}
hasEdge(x: number, y: number): boolean {
return !!this.getEdge(x, y);
}
*inEdges(vertex: number) {
const { vertices } = this;
for (let i = 0; i < vertices; i++) {
if (this.getEdge(i, vertex)) yield i;
}
}
isFull(): boolean {
return false;
}
*outEdges(vertex: number) {
const { vertices } = this;
for (let i = 0; i < vertices; i++) {
if (this.getEdge(vertex, i)) yield i;
}
}
removeEdge(x: number, y: number): this {
const [bucket, position] = this.getCoordinates(x, y);
if (Number.isNaN(bucket)) return this;
this[bucket] = this[bucket] & ~(1 << position);
return this;
}
}