Skip to content
Open
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
41 changes: 39 additions & 2 deletions Graphs/KruskalMST.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
/**
* Disjoint Set Node to store the parent and rank.
*
* A new node is the root of its own one-element set: its `parent` is itself
* and its `rank` (an upper bound on the height of its tree) is 0.
*
* The decisive state transition happens in `DisjointSetTree.link`: when two
* roots of equal rank are joined, the first root's `parent` is set to the
* second root and the second root's `rank` goes up by 1. When the ranks
* differ, the lower-rank root is attached below the higher one and no rank
* changes. `findSet` then answers "which set?" by following `parent` links
* up to the root.
*
* The example below is executed by Graphs/test/KruskalMST.test.js, which
* checks each printed value against the comment on the same line.
*
* @example
* import { DisjointSetTreeNode, DisjointSetTree } from './KruskalMST.js'
*
* const node = new DisjointSetTreeNode('a')
* console.log(node.key, node.parent === node, node.rank) // a true 0
*
* const sets = new DisjointSetTree()
* sets.makeSet('a')
* sets.makeSet('b')
* sets.makeSet('c')
* // equal ranks (0, 0): a.parent = b and b.rank becomes 1
* sets.union('a', 'b')
* console.log(sets.findSet('a').key, sets.map.b.rank) // b 1
* // ranks differ (c: 0, root b: 1): c goes below b, b.rank stays 1
* sets.union('c', 'a')
* console.log(sets.findSet('c').key, sets.map.b.rank) // b 1
* console.log(sets.map.a.rank, sets.map.c.rank) // 0 0
*/
class DisjointSetTreeNode {
// Disjoint Set Node to store the parent and rank
constructor(key) {
this.key = key
this.parent = this
Expand Down Expand Up @@ -105,7 +138,11 @@ class GraphWeightedUndirectedAdjacencyList {
}
}

export { GraphWeightedUndirectedAdjacencyList }
export {
GraphWeightedUndirectedAdjacencyList,
DisjointSetTreeNode,
DisjointSetTree
}

// const graph = new GraphWeightedUndirectedAdjacencyList()
// graph.addEdge(1, 2, 1)
Expand Down
118 changes: 118 additions & 0 deletions Graphs/test/KruskalMST.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import { readFileSync } from 'fs'
import * as KruskalModule from '../KruskalMST'
import {
DisjointSetTreeNode,
DisjointSetTree,
GraphWeightedUndirectedAdjacencyList
} from '../KruskalMST'

// Pull the @example block out of the DisjointSetTreeNode JSDoc
// (KruskalMST.js, above the class) so the documentation itself is executed.
const readDocExample = () => {
const source = readFileSync(
new URL('../KruskalMST.js', import.meta.url),
'utf8'
)
const start = source.indexOf('@example')
const end = source.indexOf('*/', start)
const lines = source
.slice(start + '@example'.length, end)
.split('\n')
.map((line) => line.replace(/^\s*\* ?/, ''))
const importLine = lines.find((line) => line.startsWith('import '))
const [, names, from] = importLine.match(/^import \{ (.+) \} from '(.+)'$/)
return {
importedNames: names.split(',').map((name) => name.trim()),
importedFrom: from,
body: lines.filter((line) => !line.startsWith('import ')).join('\n'),
documented: lines
.filter((line) => line.includes('console.log('))
.map((line) => line.split('// ')[1].trim())
}
}

describe('DisjointSetTreeNode documentation example', () => {
const example = readDocExample()

it('imports real public names from this file', () => {
expect(example.importedFrom).toBe('./KruskalMST.js')
expect(example.importedNames).toEqual([
'DisjointSetTreeNode',
'DisjointSetTree'
])
for (const name of example.importedNames) {
expect(typeof KruskalModule[name]).toBe('function')
}
})

it('prints exactly what the comments next to each console.log say', () => {
const printed = []
const fakeConsole = {
log: (...args) => printed.push(args.map(String).join(' '))
}
// Run the example body with exactly the names its import line binds.
new Function(...example.importedNames, 'console', example.body)(
...example.importedNames.map((name) => KruskalModule[name]),
fakeConsole
)

// The documented output, pinned so the doc cannot drift silently.
expect(example.documented).toEqual(['a true 0', 'b 1', 'b 1', '0 0'])
expect(printed).toEqual(['a true 0', 'b 1', 'b 1', '0 0'])
})
})

describe('DisjointSetTreeNode states (calculated by hand)', () => {
// Precondition: constructor sets parent = this and rank = 0
// (KruskalMST.js lines 38-39).
it('smallest valid input: a new node is the root of its own set', () => {
const node = new DisjointSetTreeNode('a')
expect(node.key).toBe('a')
expect(node.parent).toBe(node)
expect(node.rank).toBe(0)
})

// Precondition: link joins x below y and bumps y.rank only on equal ranks
// (KruskalMST.js lines 68-78).
it('ordinary input: union of equal ranks, then unequal ranks', () => {
const sets = new DisjointSetTree()
sets.makeSet('a')
sets.makeSet('b')
sets.makeSet('c')

sets.union('a', 'b') // ranks 0 and 0
expect(sets.map.a.parent).toBe(sets.map.b)
expect(sets.map.b.parent).toBe(sets.map.b)
expect([sets.map.a.rank, sets.map.b.rank, sets.map.c.rank]).toEqual([
0, 1, 0
])

sets.union('c', 'a') // root c has rank 0, root b has rank 1
expect(sets.map.c.parent).toBe(sets.map.b)
expect(sets.findSet('c')).toBe(sets.map.b)
expect([sets.map.a.rank, sets.map.b.rank, sets.map.c.rank]).toEqual([
0, 1, 0
])
})
})

describe('KruskalMST example from the bottom of KruskalMST.js', () => {
it('keeps the 4 cheapest edges that do not form a cycle', () => {
const graph = new GraphWeightedUndirectedAdjacencyList()
graph.addEdge(1, 2, 1)
graph.addEdge(2, 3, 2)
graph.addEdge(3, 4, 1)
graph.addEdge(3, 5, 100) // Removed in MST
graph.addEdge(4, 5, 5)

// Sorted edges: 1-2 (1), 3-4 (1), 2-3 (2), 4-5 (5), 3-5 (100).
// The first four join new sets; 3-5 would close a cycle.
expect(graph.KruskalMST().connections).toEqual({
1: { 2: 1 },
2: { 1: 1, 3: 2 },
3: { 2: 2, 4: 1 },
4: { 3: 1, 5: 5 },
5: { 4: 5 }
})
})
})
79 changes: 79 additions & 0 deletions work/R50-T007/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# R50-T007 — Runnable example for `DisjointSetTreeNode`

Source: `Graphs/KruskalMST.js`, `DisjointSetTreeNode` (line 35 after this change; line 1 at pinned commit `5c39e87`).

## Recorded contract (before any change)

| Aspect | Observation |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Input | `key` (any value used as a set member name). |
| Result | node with `key`, `parent === this` and `rank === 0` (lines 38-39): the root of a one-element set. |
| Mutation | none by itself; `DisjointSetTree.link` (lines 68-78) later rewrites `parent` and `rank`. |
| External dependencies | none. |
| Public interface | `GraphWeightedUndirectedAdjacencyList` unchanged; `DisjointSetTreeNode` and `DisjointSetTree` are now also exported so the example can import them by their real names. |

There was no test file for `KruskalMST.js` before this change.

## Hand-calculated states (written before running), then compared with a traced run

| Step | parents of a, b, c | ranks of a, b, c | Why |
| ------------------------------ | ------------------ | ---------------- | --------------------------------------------------- |
| `new DisjointSetTreeNode('a')` | a → itself | 0 | constructor, lines 38-39 |
| `makeSet` a, b, c | a, b, c | 0, 0, 0 | three roots |
| `union('a', 'b')` | **b**, b, c | 0, **1**, 0 | equal ranks: `x.parent = y`, `y.rank += 1` (73-75) |
| `union('c', 'a')` | b, b, **b** | 0, 1, 0 | find(a) = b; rank 0 < 1, so c goes below b, no bump |

`trace.txt` holds the traced execution; it matched every row.

**Decisive transition:** joining two roots of _equal_ rank is the only step that raises a rank.
Everything else is either following `parent` links (`findSet`) or hanging a shorter tree under a
taller one with no rank change.

## Executable documentation

The JSDoc above `DisjointSetTreeNode` (lines 1-34) contains an `@example` with `console.log` lines,
each followed by a comment showing what it prints. It is executed in two independent ways:

1. **In the normal test suite** (`Graphs/test/KruskalMST.test.js`). The test reads the block
straight from the source file and checks that its `import` line names real exports of
`./KruskalMST.js` (`DisjointSetTreeNode`, `DisjointSetTree`). It then runs the example body
with exactly those bindings and a captured `console`, and asserts the printed lines equal the
documented ones: `a true 0`, `b 1`, `b 1`, `0 0`.
2. **Verbatim with Node** (`evidence.mjs`, run by `check.py`). The example is written unchanged,
import line included, into a temporary ES module next to a copy of `KruskalMST.js`, run with
`node`, and its real stdout is compared with the documented comments.

If either the documentation or the code drifts, both checks fail.

The test file also asserts the hand-calculated states above, and turns the commented-out example
at the bottom of `KruskalMST.js` into an asserted MST: edges 1-2, 3-4, 2-3 and 4-5 are kept, and
3-5 is skipped because it would close a cycle.

## Sensitivity check (temporary copy only)

`check.py` changes `y.rank += 1` to `y.rank += 2` in a temp copy; the doc-example test fails (prints
`b 2`, documented `b 1`). The real source is untouched.

## How to run

From the repository root:

```sh
python3 work/R50-T007/check.py
```

`check.py` installs dependencies from `package-lock.json`, runs the focused test file, evaluates the fixture with `evidence.mjs` (input, expected, actual and source line for every case), runs each deliberate mutant in a temporary copy, and finally runs the repository test script in non-watch mode (`npm test`, which is `vitest run`). It exits non-zero if any assertion or step fails, and records every command it ran in `commands.log`.

### Recorded run (files in this folder)

| Step | Command | Result |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Install from lockfile | `npm ci --ignore-scripts --no-audit --no-fund` (exit 0) | ok |
| Focused tests | `node_modules/.bin/vitest run Graphs/test/KruskalMST.test.js --reporter=json --outputFile=work/R50-T007/vitest-focused.raw.json` | 5/5 passed |
| Fixture evidence | `node work/R50-T007/evidence.mjs` | 7/7 rows match |
| Mutant: rank grows by 2 on equal-rank link | temporary copy | killed by `prints exactly what the comments next to each console.log say` |
| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T007/vitest-full.raw.json` | 11975/11975 passed |

Tool versions (`versions.txt`): python 3.12.10; node v26.13.1; npm 11.20.0; platform macOS-27.2.1-arm64-arm-64bit; vitest vitest/1.2.1 darwin-arm64 node-v26.13.1.

Files: `results.json` (all of the above, machine-readable), `vitest-focused.json` (each focused test and its status), `commands.log`, `versions.txt`.
Loading