Skip to content

Instantly share code, notes, and snippets.

@Phryxia
Last active May 15, 2024 02:55
Show Gist options
  • Save Phryxia/0273f941805e781cee2680999060114f to your computer and use it in GitHub Desktop.
Save Phryxia/0273f941805e781cee2680999060114f to your computer and use it in GitHub Desktop.
TypeScript implementation of simple SymmetricMatrix
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;
}
}
}
}
@Phryxia
Copy link
Author

Phryxia commented Aug 9, 2023

This is an implementation for symmetric matrix for arbitrary type T. This only uses N * (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 and j is index of column with zero based.

0
1        2
3        4        5
...
∑i      (∑i)+1  ...  (∑i)+j

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment