Last active
May 15, 2024 02:55
-
-
Save Phryxia/0273f941805e781cee2680999060114f to your computer and use it in GitHub Desktop.
TypeScript implementation of simple SymmetricMatrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class SymmetricMatrix<T> { | |
protected data: T[]; | |
constructor( | |
public readonly size: number, | |
initializer: (i: number, j: number) => T, | |
) { | |
this.data = new Array(size); | |
for (let i = 0; i < size; ++i) { | |
for (let j = 0; j <= i; ++j) { | |
this.set(i, j, initializer(i, j)); | |
} | |
} | |
} | |
// i-th row, j-th column | |
set(i: number, j: number, value: T) { | |
return (this.data[this.get1DIndex(i, j)] = value); | |
} | |
get(i: number, j: number) { | |
return this.data[this.get1DIndex(i, j)]; | |
} | |
private get1DIndex(i: number, j: number) { | |
if (i < j) { | |
const temp = i; | |
i = j; | |
j = temp; | |
} | |
return (i * (i + 1)) / 2 + j; | |
} | |
[Symbol.iterator]() { | |
return this.data[Symbol.iterator](); | |
} | |
/** | |
* Iterate every elements with rich indices | |
* Abort if returned value is false | |
* @param callback | |
*/ | |
forEach(callback: (value: T, i: number, j: number) => boolean | undefined) { | |
for (let i = 0; i < this.size; ++i) { | |
for (let j = 0; j <= i; ++j) { | |
if (callback(this.get(i, j), i, j) === false) return; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an implementation for symmetric matrix for arbitrary type
T
. This only usesN * (N - 1) / 2
spaces. Also this doesn't use 2D array so that less overhead exists.The index of 2D coordinate is computed by following manner, where
i
is index of row andj
is index of column with zero based.