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
16 changes: 15 additions & 1 deletion Data-Structures/Heap/KeyPriorityQueue.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@
*/

// Priority Queue Helper functions

/**
* Returns the array index of the parent of the node stored at `position`.
*
* Example: getParentPosition(4) === 1, because node 1 has children at
* 2 * 1 + 1 = 3 and 2 * 1 + 2 = 4. Siblings share a parent:
* getParentPosition(3) === getParentPosition(4) === 1.
*
* The root (position 0) has no parent and yields -1, which callers treat as
* "no parent" via their `parentPos >= 0` checks.
*
* @param {number} position non-negative integer index into the heap array
* @returns {number} parent index, or -1 for the root
*/
const getParentPosition = (position) => Math.floor((position - 1) / 2)
const getChildrenPositions = (position) => [2 * position + 1, 2 * position + 2]

Expand Down Expand Up @@ -154,4 +168,4 @@ class KeyPriorityQueue {
}
}

export { KeyPriorityQueue }
export { KeyPriorityQueue, getParentPosition }
93 changes: 92 additions & 1 deletion Data-Structures/Heap/test/KeyPriorityQueue.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { KeyPriorityQueue } from '../KeyPriorityQueue.js'
import { KeyPriorityQueue, getParentPosition } from '../KeyPriorityQueue.js'

describe('Key Priority Queue', () => {
describe('Method isEmpty', () => {
Expand Down Expand Up @@ -124,3 +124,94 @@ describe('Key Priority Queue', () => {
})
})
})

// Reference comparison for getParentPosition (KeyPriorityQueue.js line 36).
describe('getParentPosition against independent references', () => {
// Reviewed explicit table, written by hand from the heap layout described
// at lines 12-16: children of p are 2p + 1 and 2p + 2, so positions
// (1, 2) -> 0, (3, 4) -> 1, (5, 6) -> 2, ... and the root has no parent (-1).
const expectedParents = [
-1, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11,
11
]

test.each(expectedParents.map((parent, position) => [position, parent]))(
'explicit table: parent of position %i is %i',
(position, parent) => {
expect(getParentPosition(position)).toBe(parent)
}
)

// Different method: in 1-based heap numbering the parent of k is k >> 1,
// so the 0-based parent of p is ((p + 1) >> 1) - 1. No division or floor.
test('bit-shift oracle agrees for positions 0..63', () => {
const oracle = (p) => ((p + 1) >> 1) - 1
const mismatches = []
for (let p = 0; p < 64; p++) {
if (getParentPosition(p) !== oracle(p)) {
mismatches.push([p, getParentPosition(p), oracle(p)])
}
}
expect(mismatches).toEqual([])
})

test('representative result: getParentPosition(4) is 1', () => {
expect(getParentPosition(4)).toBe(1)
expect(getParentPosition(3)).toBe(getParentPosition(4))
})
})

describe('queue order relying on getParentPosition', () => {
// Increasing priorities make the min-heap behave first-in, first-out.
// Each step lists the explicit expected removed key and queue size; a
// plain array (independent FIFO reference) must agree after every step.
test('enqueue A, B, C; remove twice; insert D; drain -> A, B, C, D', () => {
const steps = [
{ op: 'push', key: 'A', priority: 1, size: 1 },
{ op: 'push', key: 'B', priority: 2, size: 2 },
{ op: 'push', key: 'C', priority: 3, size: 3 },
{ op: 'pop', removed: 'A', size: 2 },
{ op: 'pop', removed: 'B', size: 1 },
{ op: 'push', key: 'D', priority: 4, size: 2 },
{ op: 'pop', removed: 'C', size: 1 },
{ op: 'pop', removed: 'D', size: 0 }
]
const queue = new KeyPriorityQueue()
const reference = []
expect(queue.isEmpty()).toBe(true)

const removed = []
for (const step of steps) {
if (step.op === 'push') {
queue.push(step.key, step.priority)
reference.push(step.key)
} else {
const key = queue.pop()
expect(key).toBe(step.removed)
expect(key).toBe(reference.shift())
removed.push(key)
}
expect(queue.priorities.size).toBe(step.size)
expect(reference.length).toBe(step.size)
expect(queue.isEmpty()).toBe(step.size === 0)
}

expect(removed).toEqual(['A', 'B', 'C', 'D'])
expect(queue.contains('A')).toBe(false)
})

test('separate instances do not share contents', () => {
const first = new KeyPriorityQueue()
const second = new KeyPriorityQueue()
first.push('A', 1)
expect(first.isEmpty()).toBe(false)
expect(second.isEmpty()).toBe(true)
expect(second.contains('A')).toBe(false)

second.push('B', 1)
expect(first.pop()).toBe('A')
expect(first.isEmpty()).toBe(true)
expect(second.contains('B')).toBe(true)
expect(second.priorities.size).toBe(1)
})
})
81 changes: 81 additions & 0 deletions work/R50-T003/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# R50-T003 — Cross-check `getParentPosition` against an independent reference

Source: `Data-Structures/Heap/KeyPriorityQueue.js`, `getParentPosition` (line 36 after this change; line 22 at pinned commit `5c39e87`).

## Recorded contract (before any change)

| Aspect | Observation |
| --------------------- | ------------------------------------------------------------------------------------------------- |
| Input | `position`: non-negative integer index into the heap array (layout described at lines 12-16). |
| Result | `Math.floor((position - 1) / 2)`; the root (0) yields `-1`, read as "no parent" (lines 105, 126). |
| Mutation | None. Pure helper. |
| External dependencies | `Math.floor` only. |
| Public interface | `KeyPriorityQueue` unchanged; `getParentPosition` is now also exported so it can be tested. |

## Oracles (neither calls the function under test)

1. **Reviewed explicit table** for positions 0..24 (25 inputs), written by hand from "children of
`p` are `2p + 1` and `2p + 2`": `-1, 0, 0, 1, 1, 2, 2, …, 11, 11`.
2. **Different method**: in 1-based heap numbering the parent of `k` is `k >> 1`, so the 0-based
parent of `p` is `((p + 1) >> 1) - 1`. Compared for positions 0..63.

Result: no mismatch on any of the 89 compared positions. No implementation change was needed.

## Fixture (queue behaviour that depends on `getParentPosition`)

Increasing priorities make the min-heap first-in, first-out. After **every** operation the test
checks the explicit expected key and size, and also compares with an independent reference: a
plain JavaScript array used as a FIFO queue (`push` / `shift`). Size is read from the public
`priorities` map.

| Step | Operation | Expected removed | Expected size |
| ---- | --------- | ---------------- | ------------------------------------------------ |
| 0 | new queue | — | 0 (`isEmpty() === true`) |
| 1 | push A(1) | — | 1 |
| 2 | push B(2) | — | 2 |
| 3 | push C(3) | — | 3 |
| 4 | pop | A | 2 |
| 5 | pop | B | 1 |
| 6 | push D(4) | — | 2 |
| 7 | pop | C | 1 |
| 8 | pop | D | 0 (`isEmpty() === true`, documented empty state) |

Removal order: A, B, C, D. Separate instances: pushing into or popping from one queue never changes
another (checked in both directions).

## Sensitivity check (temporary copy only)

`check.py` copies the source and test into a temp dir and replaces the formula with
`Math.floor(position / 2)`. The minimal reproducible case is `getParentPosition(0)`: expected `-1`,
mutant `0`. The named test `explicit table: parent of position 0 is -1` fails, along with the existing
push/pop tests. The real source is never modified.

## Observation, not changed (out of scope)

`pop()` on an empty queue returns `undefined` and stays empty (`isEmpty() === true`), but
`_swap(0, -1)` leaves a stray `"-1"` property on the internal `_heap` array. This is undocumented
behaviour that does not affect `getParentPosition`, so it is only recorded here (`baseline.txt`).

## How to run

From the repository root:

```sh
python3 work/R50-T003/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 Data-Structures/Heap/test/KeyPriorityQueue.test.js --reporter=json --outputFile=work/R50-T003/vitest-focused.raw.json` | 38/38 passed |
| Fixture evidence | `node work/R50-T003/evidence.mjs` | 36/36 rows match |
| Mutant: parent formula off by one (floor(p / 2)) | temporary copy | killed by `explicit table: parent of position 0 is -1` |
| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T003/vitest-full.raw.json` | 11999/11999 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`.
2 changes: 2 additions & 0 deletions work/R50-T003/baseline.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fixture removal order: A,B,C,D isEmpty: true
pop on empty -> undefined isEmpty after: true heap length: 0 own keys: ["-1"]
Loading