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
29 changes: 27 additions & 2 deletions Sorts/OddEvenSort.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,38 @@
for more information : https://en.wikipedia.org/wiki/Odd%E2%80%93even_sort
*/

// Helper function to swap array items
function swap(arr, i, j) {
/**
* Helper function to swap array items in place.
*
* Invariant: a swap only exchanges two positions, so the multiset of values
* in `arr` (every value and how many times it occurs) never changes.
* This is what lets oddEvenSort return a permutation of its input.
*
* @param {Array} arr array to modify in place
* @param {number} i first index
* @param {number} j second index
* @returns {undefined} nothing; `arr` is mutated
* @example const a = [3, 1, 2]; swap(a, 0, 1) // a is now [1, 3, 2]
*/
export function swap(arr, i, j) {
const tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
}

/**
* Sorts `arr` in ascending order, in place, and returns the same array.
*
* Invariants checked by the tests:
* - the result is ordered: result[k] <= result[k + 1] for every k;
* - the result has the same multiset of values as the input (only `swap`
* moves values);
* - the returned array is the input array (`oddEvenSort(a) === a`).
*
* @param {number[]} arr array of mutually comparable numbers
* @returns {number[]} the same array, now sorted ascending
* @example oddEvenSort([3, 1, 2]) // [1, 2, 3]
*/
export function oddEvenSort(arr) {
let sorted = false
while (!sorted) {
Expand Down
127 changes: 126 additions & 1 deletion Sorts/test/OddEvenSort.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { oddEvenSort } from '../OddEvenSort'
import { oddEvenSort, swap } from '../OddEvenSort'

test('The OddEvenSort of the array [5, 4, 3, 2, 1] is [1, 2, 3, 4, 5]', () => {
const arr = [5, 4, 3, 2, 1]
Expand All @@ -23,3 +23,128 @@ test('The OddEvenSort of the array [166, 169, 144] is [144, 166, 169]', () => {
const res = oddEvenSort(arr)
expect(res).toEqual([144, 166, 169])
})

// Invariant tests for swap (OddEvenSort.js line 22) and the sort built on it.
// Domain (JSDoc at lines 28-40, comparisons at lines 46 and 52): arrays of mutually
// comparable numbers. The generator only produces finite integers.

// Small deterministic PRNG (mulberry32) so every run sees the same cases.
const mulberry32 = (seed) => () => {
seed = (seed + 0x6d2b79f5) | 0
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}

const SEED = 20261123
const generateCases = (count) => {
const random = mulberry32(SEED)
const cases = []
for (let n = 0; n < count; n++) {
const length = Math.floor(random() * 13) // 0..12 items
const values = []
for (let k = 0; k < length; k++) {
values.push(Math.floor(random() * 11) - 5) // -5..5, repeats likely
}
cases.push(values)
}
return cases
}

const isOrdered = (arr) => arr.every((v, k) => k === 0 || arr[k - 1] <= v)
const counts = (arr) => {
const map = new Map()
for (const v of arr) map.set(v, (map.get(v) || 0) + 1)
return [...map.entries()].sort((a, b) => a[0] - b[0])
}

describe('swap invariant', () => {
test('swap exchanges two positions in place and returns undefined', () => {
const arr = [3, 1, 2]
expect(swap(arr, 0, 1)).toBeUndefined()
expect(arr).toEqual([1, 3, 2])
})

test('swap preserves multiplicities', () => {
const arr = [2, 2, 1]
swap(arr, 1, 2)
expect(arr).toEqual([2, 1, 2])
expect(counts(arr)).toEqual([
[1, 1],
[2, 2]
])
})
})

describe('oddEvenSort fixture (ascending, in place)', () => {
test.each([
[
[3, 1, 2],
[1, 2, 3]
],
[
[2, 2, 1],
[1, 2, 2]
],
[
[1, 2, 3],
[1, 2, 3]
],
[
[3, 2, 1],
[1, 2, 3]
],
[[], []],
[[7], [7]]
])('oddEvenSort(%j) is %j and returns the same array', (input, expected) => {
const arr = [...input]
const result = oddEvenSort(arr)
expect(result).toEqual(expected)
expect(result).toBe(arr)
})
})

describe('oddEvenSort properties over 100 seeded cases', () => {
const cases = generateCases(100)

// On failure, report the shortest failing input so it stays readable.
const smallestFailing = (fails) =>
cases.filter(fails).sort((a, b) => a.length - b.length)[0]

test('the generator is deterministic for a fixed seed', () => {
expect(cases.length).toBe(100)
// Pinned literal values for seed 20261123 (first case and two readable
// small cases, one with a repeated value).
expect(cases[0]).toEqual([4, 0, -1, -2, 0, -1, -5, 1, -4, 0, -3])
expect(cases[10]).toEqual([-2, 5, 5])
expect(cases[33]).toEqual([3, 5, -2])
// The smallest supported collection (empty) is generated 4 times.
expect(cases.filter((c) => c.length === 0).length).toBe(4)
})

test('readable small generated cases sort as expected', () => {
expect(oddEvenSort([...cases[10]])).toEqual([-2, 5, 5])
expect(oddEvenSort([...cases[33]])).toEqual([-2, 3, 5])
})

test('output is ordered', () => {
const failing = smallestFailing((c) => !isOrdered(oddEvenSort([...c])))
expect(failing).toBeUndefined()
})

test('output preserves input multiplicities', () => {
const failing = smallestFailing(
(c) =>
JSON.stringify(counts(oddEvenSort([...c]))) !==
JSON.stringify(counts(c))
)
expect(failing).toBeUndefined()
})

test('output is the input array, mutated in place', () => {
for (const c of cases) {
const arr = [...c]
expect(oddEvenSort(arr)).toBe(arr)
}
})
})
86 changes: 86 additions & 0 deletions work/R50-T004/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# R50-T004 — Invariant tests for `swap` (Odd–Even Sort)

Source: `Sorts/OddEvenSort.js`, `swap` (line 22 after this change; line 10 at pinned commit `5c39e87`).

## Recorded contract (before any change)

| Aspect | `swap(arr, i, j)` | `oddEvenSort(arr)` |
| --------------------- | ---------------------------------------- | -------------------------------------------------------- |
| Inputs | array, two indices | array of mutually comparable numbers (compared with `>`) |
| Result | `undefined` | the **same** array, sorted ascending (`return arr`) |
| Mutation | exchanges `arr[i]` and `arr[j]` in place | sorts `arr` in place |
| External dependencies | none | none |

`swap` is now exported (with JSDoc) so the invariant can be tested directly. The sort keeps its
ascending interface; no descending mode exists in the source.

## Invariant and why it holds

`swap` only exchanges two positions, so the multiset of values (each value and its count) never
changes. `oddEvenSort` moves values **only** through `swap`, and stops only when a full odd pass and a
full even pass make no swap, i.e. no adjacent pair is out of order. Hence the output is:

1. ordered: `out[k] <= out[k + 1]`;
2. a permutation of the input (same multiplicities);
3. the input array itself (`oddEvenSort(a) === a`).

## Fixture (expected values written before running)

| Input | Expected |
| --------------- | ----------- |
| `[3, 1, 2]` | `[1, 2, 3]` |
| `[2, 2, 1]` | `[1, 2, 2]` |
| `[1, 2, 3]` | `[1, 2, 3]` |
| `[3, 2, 1]` | `[1, 2, 3]` |
| `[]` (smallest) | `[]` |
| `[7]` | `[7]` |

`swap([3, 1, 2], 0, 1)` → array becomes `[1, 3, 2]`, returns `undefined`.

## Generator

100 cases from a mulberry32 PRNG with fixed seed `20261123`; length 0..12, integers -5..5, so
repeated values are common (62 of the 100 cases contain a repeat) and the smallest supported
collection `[]` appears 4 times. Only finite integers are generated. `NaN`, mixed types and holes
are outside the comparable-number domain (`>` comparisons at lines 46 and 52), so the generator
never produces them.

The test pins literal generated values so determinism is asserted against explicit expectations:
case 0 is `[4, 0, -1, -2, 0, -1, -5, 1, -4, 0, -3]`. Two readable small cases are retained with
explicit sorted outputs: case 10 `[-2, 5, 5]` → `[-2, 5, 5]` and case 33 `[3, 5, -2]` →
`[-2, 3, 5]`. If a property ever fails, the test reports the shortest failing input.

## Deliberately broken copies (temporary directory only)

| Mutant | Smallest readable failing case | Named assertion that fails |
| ------------------------------------------ | ------------------------------ | --------------------------------------- |
| `swap`: `arr[j] = tmp` → `arr[j] = arr[i]` | `[2, 1]` → `[1, 1]` | `output preserves input multiplicities` |
| even pass no longer sets `sorted = false` | `[3, 1, 2]` → `[1, 3, 2]` | `output is ordered` |

Both mutants are applied by `check.py` to copies in a temp dir; the real source is never edited.
Baseline: all fixture values and both properties held on the unmodified implementation; no defect.

## How to run

From the repository root:

```sh
python3 work/R50-T004/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 Sorts/test/OddEvenSort.test.js --reporter=json --outputFile=work/R50-T004/vitest-focused.raw.json` | 17/17 passed |
| Fixture evidence | `node work/R50-T004/evidence.mjs` | 8/8 rows match |
| Mutant: swap loses a value (arr[j] = arr[i]) | temporary copy | killed by `output preserves input multiplicities` |
| Mutant: even pass no longer clears the sorted flag | temporary copy | killed by `output is ordered` |
| Repository test script | `npm test -- --reporter=json --outputFile=work/R50-T004/vitest-full.raw.json` | 11983/11983 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