-
Notifications
You must be signed in to change notification settings - Fork 21
/
adjacency-matrix-weighted-directed.ts
107 lines (90 loc) · 2.59 KB
/
adjacency-matrix-weighted-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
107
import type {
AdjacencyStructure,
AdjacencyStructureConstructor,
IndexedCollection,
TypedArrayConstructors,
} from "./utility-types.ts";
/**
* Creates an Adjacency Matrix class extending a given TypedArray class.
*
* @param Base a TypedArray class to extend
*/
export function AdjacencyMatrixWeightedDirectedMixin<
U extends TypedArrayConstructors,
>(Base: U): AdjacencyStructureConstructor<U> {
// deno-lint-ignore no-empty-interface
interface AdjacencyMatrixWeightedDirected extends IndexedCollection {}
/**
* Implements Adjacency Matrix for weighted directed graphs.
*/
class AdjacencyMatrixWeightedDirected extends Base
implements AdjacencyStructure {
static directed = true;
static weighted = true;
empty = 0;
static get [Symbol.species](): U {
return Base;
}
_vertices = 0;
get vertices() {
return (
this._vertices ||
(this._vertices = (this
.constructor as typeof AdjacencyMatrixWeightedDirected).getVertices(
this.length,
)), this._vertices
);
}
get edges() {
return this.vertices ** 2;
}
static create<
T extends AdjacencyStructureConstructor<TypedArrayConstructors>,
>(vertices: number): InstanceType<T> {
const length = this.getLength(vertices);
return new this(length) as InstanceType<T>;
}
static getLength(vertices: number): number {
return vertices * vertices;
}
protected static getVertices(length: number): number {
return Math.sqrt(length);
}
addEdge(x: number, y: number, weight: number): this {
this[this.getIndex(x, y)] = weight;
return this;
}
getEdge(x: number, y: number) {
return this[this.getIndex(x, y)];
}
getIndex(x: number, y: number): number {
return x * this.vertices + y;
}
hasEdge(x: number, y: number) {
const edge = this.getEdge(x, y);
return edge !== undefined && edge !== this.empty;
}
*inEdges(vertex: number) {
const { vertices } = this;
for (let i = 0; i < vertices; i++) {
if (this.hasEdge(i, vertex)) yield i;
}
}
isFull(): boolean {
return false;
}
*outEdges(vertex: number) {
const { vertices } = this;
const offset = vertex * vertices;
for (let i = 0; i < vertices; i++) {
const edge = this[offset + i];
if (edge !== undefined && edge !== this.empty) yield i;
}
}
removeEdge(x: number, y: number): this {
this[this.getIndex(x, y)] = this.empty;
return this;
}
}
return AdjacencyMatrixWeightedDirected;
}