Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions src/data-structures/disjoint-set/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, test } from 'vitest';
import { DisjointSet } from './index.js';

describe('DisjointSet', () => {
test('initialize', () => {
const ds = new DisjointSet(5);
for (let i = 0; i < 5; i += 1) {
expect(ds.find(i)).toBe(i);
}
});

test('union', () => {
const ds = new DisjointSet(5);
expect(ds.union(0, 1)).toBe(true);
expect(ds.connected(0, 1)).toBe(true);
expect(ds.connected(1, 0)).toBe(true);
});

test('already connected elements', () => {
const ds = new DisjointSet(5);
ds.union(0, 1);
expect(ds.union(0, 1)).toBe(false);
});

test('multiple unions', () => {
const ds = new DisjointSet(5);
ds.union(0, 1);
ds.union(1, 2);
ds.union(3, 4);

expect(ds.connected(0, 2)).toBe(true);
expect(ds.connected(0, 3)).toBe(false);
expect(ds.connected(3, 4)).toBe(true);

ds.union(2, 4);
expect(ds.connected(0, 4)).toBe(true);
});

test('unrelated elements', () => {
const ds = new DisjointSet(5);
ds.union(0, 1);
ds.union(2, 3);

expect(ds.connected(0, 2)).toBe(false);
expect(ds.connected(1, 3)).toBe(false);
expect(ds.connected(4, 4)).toBe(true);
});
});
40 changes: 40 additions & 0 deletions src/data-structures/disjoint-set/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export class DisjointSet {
#parent;

#rank;

constructor(size: number) {
this.#parent = Array.from({ length: size }, (_, i) => i);
this.#rank = new Uint32Array(size);
}

find(x: number) {
if (this.#parent[x] !== x) {
this.#parent[x] = this.find(this.#parent[x]);
}

return this.#parent[x];
}

union(a: number, b: number) {
const rootA = this.find(a);
const rootB = this.find(b);

if (rootA === rootB) return false;

if (this.#rank[rootA] < this.#rank[rootB]) {
this.#parent[rootA] = rootB;
} else if (this.#rank[rootA] > this.#rank[rootB]) {
this.#parent[rootB] = rootA;
} else {
this.#parent[rootB] = rootA;
this.#rank[rootA] += 1;
}

return true;
}

connected(a: number, b: number) {
return this.find(a) === this.find(b);
}
}
6 changes: 4 additions & 2 deletions src/shared/abstract-linked-list/abstract-linked-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,10 @@ export abstract class AbstractLinkedList<

protected _isMatch(value: T, matcher: T | Predicate<T>) {
return isFunction(matcher)
? matcher(value)
: this._comparator.equal(matcher, value);
? // @ts-ignore
matcher(value)
: // @ts-ignore
this._comparator.equal(matcher, value);
}

protected _findNodeByIndex(index: number) {
Expand Down