From 37ba01f893b8daabf646180ab2ad973a4a30c284 Mon Sep 17 00:00:00 2001 From: Aniruddha Bongale Date: Sun, 22 Nov 2026 11:48:03 +0530 Subject: [PATCH] test(search): define supported boundaries of quickSelectSearch (R50-T042) --- Search/QuickSelectSearch.js | 38 +-- Search/test/QuickSelectSearch.test.js | 114 ++++++++ work/R50-T042/check.py | 361 ++++++++++++++++++++++++++ work/R50-T042/results.json | 109 ++++++++ 4 files changed, 606 insertions(+), 16 deletions(-) create mode 100644 Search/test/QuickSelectSearch.test.js create mode 100644 work/R50-T042/check.py create mode 100644 work/R50-T042/results.json diff --git a/Search/QuickSelectSearch.js b/Search/QuickSelectSearch.js index c332af6721..3f2f9a733f 100644 --- a/Search/QuickSelectSearch.js +++ b/Search/QuickSelectSearch.js @@ -1,15 +1,28 @@ -/* - * Places the `k` smallest elements in `array` in the first `k` indices: `[0..k-1]` - * Modifies the passed in array *in place* - * Returns a slice of the wanted elements for convenience - * Efficient mainly because it never performs a full sort. +/** + * Quickselect algorithm to place the `k`-th smallest element in its final sorted index `k`, + * partitioning elements in-place: all elements at indices < `k` are <= array[k], and + * all elements at indices > `k` are >= array[k]. * - * The only guarantees are that: + * Supported Boundary Contract: + * - Precondition check established at Line 15: `if (!array || array.length <= k)` + * - Supported domain: + * - `array`: Non-empty Array of comparable numbers (`array.length >= 1`). + * - `k`: 0-based integer index within `[0, array.length - 1]`. + * - Smallest valid input boundary: + * - Single-element array (`array.length === 1`) with `k === 0`. + * - Upper valid domain boundary: + * - Any non-empty array with `k === array.length - 1`. + * - Unsupported domain (throws `new Error('Invalid arguments')` at Line 16): + * - Falsy arrays (`!array`): `null`, `undefined`. + * - Empty arrays (`array.length === 0 <= k`). + * - Out-of-bounds index (`k >= array.length`). * - * - The `k`th element is in its final sort index (if the array were to be sorted) - * - All elements before index `k` are smaller than the `k`th element + * @param {Array} array - The input array to partition in-place. + * @param {number} k - The 0-based target index to position (0 <= k < array.length). + * @returns {Array} The mutated array with the k-th element in its final sorted index. + * @throws {Error} 'Invalid arguments' when array is falsy or array.length <= k (Line 15). * - * [Reference](http://en.wikipedia.org/wiki/Quickselect) + * Reference: http://en.wikipedia.org/wiki/Quickselect */ export function quickSelectSearch(array, k) { if (!array || array.length <= k) { @@ -46,10 +59,3 @@ export function quickSelectSearch(array, k) { } return array } - -/* ---------------------------------- Test ---------------------------------- */ - -// const arr = [1121111, 21, 333, 41, 5, 66, 7777, 28, 19, 11110] -// quickSelectSearch(arr, 5) // [ 19, 21, 28, 41, 5, 66, 333, 11110, 1121111, 7777 ] -// quickSelectSearch(arr, 2) // [ 19, 5, 21, 41, 28, 333, 11110, 1121111, 7777, 66 ] -// quickSelectSearch(arr, 7) // [ 19, 5, 21, 41, 28, 66, 333, 7777, 11110, 1121111 ] diff --git a/Search/test/QuickSelectSearch.test.js b/Search/test/QuickSelectSearch.test.js new file mode 100644 index 0000000000..606a5e5409 --- /dev/null +++ b/Search/test/QuickSelectSearch.test.js @@ -0,0 +1,114 @@ +import { quickSelectSearch } from '../QuickSelectSearch' + +describe('quickSelectSearch', () => { + describe('Stated Fixture: Smallest valid input and ordinary input', () => { + it('handles the smallest valid input: 1-element array with k = 0 (Precondition line 15: array.length > k)', () => { + // Smallest valid input: single element array [42], target index k = 0 + const input = [42] + const k = 0 + // Independently calculated expected output: [42] where result[0] === 42 + const expected = [42] + const result = quickSelectSearch(input, k) + + expect(result).toBe(input) + expect(result[0]).toBe(expected[0]) + expect(result).toEqual(expected) + }) + + it('handles one ordinary input: unsorted array with median target index k = 4 (Precondition line 15: array.length > k)', () => { + // Ordinary input: 9 unsorted distinct elements + const input = [9, 2, 7, 4, 5, 6, 3, 8, 1] + const k = 4 + // Independently calculated expected output: + // Sorted elements would be [1, 2, 3, 4, 5, 6, 7, 8, 9] + // Element at sorted index k=4 is 5 + // Partition guarantee: all elements at indices < 4 are <= 5, all elements at indices > 4 are >= 5 + const result = quickSelectSearch(input, k) + + expect(result).toBe(input) + expect(result[4]).toBe(5) + // Check left partition (< index 4) + for (let i = 0; i < 4; i++) { + expect(result[i]).toBeLessThanOrEqual(5) + } + // Check right partition (> index 4) + for (let i = 5; i < result.length; i++) { + expect(result[i]).toBeGreaterThanOrEqual(5) + } + }) + }) + + describe('Supported Boundary Cases (Valid side of contract)', () => { + it('asserts lower supported boundary: k = 0 on multi-element array (Precondition line 15: array.length > k)', () => { + const input = [5, 1, 9, 3, 7] + const k = 0 + // Independently calculated expected: smallest element (1) at index 0 + const result = quickSelectSearch(input, k) + + expect(result[0]).toBe(1) + for (let i = 1; i < result.length; i++) { + expect(result[i]).toBeGreaterThanOrEqual(1) + } + }) + + it('asserts upper supported boundary: k = array.length - 1 (Precondition line 15: array.length > k)', () => { + const input = [5, 1, 9, 3, 7] + const k = 4 // array.length - 1 + // Independently calculated expected: largest element (9) at index 4 + const result = quickSelectSearch(input, k) + + expect(result[4]).toBe(9) + for (let i = 0; i < 4; i++) { + expect(result[i]).toBeLessThanOrEqual(9) + } + }) + + it('asserts two-element array boundaries: k = 0 and k = 1', () => { + const arr1 = [20, 10] + const res1 = quickSelectSearch(arr1, 0) + expect(res1[0]).toBe(10) + expect(res1[1]).toBe(20) + + const arr2 = [20, 10] + const res2 = quickSelectSearch(arr2, 1) + expect(res2[0]).toBe(10) + expect(res2[1]).toBe(20) + }) + + it('asserts domain boundary with duplicate elements', () => { + const input = [3, 1, 3, 2, 3] + const k = 2 + // Sorted: [1, 2, 3, 3, 3] -> element at index 2 is 3 + const result = quickSelectSearch(input, k) + + expect(result[2]).toBe(3) + for (let i = 0; i < 2; i++) { + expect(result[i]).toBeLessThanOrEqual(3) + } + for (let i = 3; i < result.length; i++) { + expect(result[i]).toBeGreaterThanOrEqual(3) + } + }) + }) + + describe('Explicitly Unsupported Boundaries (Invalid side of contract, Line 15-16)', () => { + it('throws Error("Invalid arguments") when k equals array.length (just beyond upper boundary, Line 15)', () => { + const input = [10, 20, 30] + expect(() => quickSelectSearch(input, 3)).toThrow('Invalid arguments') + }) + + it('throws Error("Invalid arguments") when k exceeds array.length (Line 15)', () => { + const input = [10, 20, 30] + expect(() => quickSelectSearch(input, 5)).toThrow('Invalid arguments') + }) + + it('throws Error("Invalid arguments") when array is empty (array.length <= k, Line 15)', () => { + expect(() => quickSelectSearch([], 0)).toThrow('Invalid arguments') + }) + + it('throws Error("Invalid arguments") when array is null or undefined (!array, Line 15)', () => { + expect(() => quickSelectSearch(null, 0)).toThrow('Invalid arguments') + expect(() => quickSelectSearch(undefined, 0)).toThrow('Invalid arguments') + }) + }) +}) diff --git a/work/R50-T042/check.py b/work/R50-T042/check.py new file mode 100644 index 0000000000..617aea8508 --- /dev/null +++ b/work/R50-T042/check.py @@ -0,0 +1,361 @@ +#!/usr/bin/env python3 +""" +Automated check runner for Task R50-T042: +Define the supported boundaries of quickSelectSearch (QuickSelectSearch.js) +""" + +import json +import os +import subprocess +import sys +import time + +def get_tool_versions(repo_root): + env = os.environ.copy() + if "/opt/homebrew/bin" not in env.get("PATH", ""): + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + + def run_cmd(cmd): + try: + res = subprocess.run(cmd, shell=True, cwd=repo_root, capture_output=True, text=True, env=env) + return res.stdout.strip() + except Exception as e: + return str(e) + + node_ver = run_cmd("node -v") + npm_ver = run_cmd("npm -v") + git_branch = run_cmd("git rev-parse --abbrev-ref HEAD") + git_commit = run_cmd("git rev-parse HEAD") + python_ver = sys.version.split()[0] + + return { + "python": python_ver, + "node": node_ver, + "npm": npm_ver, + "git_branch": git_branch, + "git_commit": git_commit + } + +def run_native_tests(repo_root): + env = os.environ.copy() + if "/opt/homebrew/bin" not in env.get("PATH", ""): + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + + cmd = "npm test -- Search/test/QuickSelectSearch.test.js" + proc = subprocess.run(cmd, shell=True, cwd=repo_root, capture_output=True, text=True, env=env) + + output = proc.stdout + "\n" + proc.stderr + passed = proc.returncode == 0 + + test_count = 0 + for line in output.splitlines(): + if "Tests" in line and "passed" in line: + parts = line.strip().split() + for p in parts: + if p.isdigit(): + test_count = int(p) + break + + return { + "command": cmd, + "exit_code": proc.returncode, + "passed": passed, + "test_count": test_count, + "output": output + } + +def run_boundary_contract_checks(repo_root): + env = os.environ.copy() + if "/opt/homebrew/bin" not in env.get("PATH", ""): + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + + js_code = """ +import { quickSelectSearch } from './Search/QuickSelectSearch.js' + +const results = { + checks: [], + allPassed: true +} + +function recordCheck(name, preconditionLine, inputDesc, expected, actual, passed, details = {}) { + results.checks.push({ + name, + precondition_source_line: preconditionLine, + input: inputDesc, + expected, + actual, + passed, + details + }) + if (!passed) { + results.allPassed = false + } +} + +// Precondition Source Line Reference: +// Search/QuickSelectSearch.js Line 15: "if (!array || array.length <= k)" +// Search/QuickSelectSearch.js Line 16: "throw new Error('Invalid arguments')" + +// Boundary Check 1: Smallest valid input (1-element array, k = 0) +try { + const input = [42] + const k = 0 + const expected = [42] + const actual = quickSelectSearch([...input], k) + const passed = actual[0] === 42 && actual.length === 1 + recordCheck( + 'Smallest valid input (1-element array, k = 0)', + 'Search/QuickSelectSearch.js:15', + 'array = [42], k = 0', + JSON.stringify(expected), + JSON.stringify(actual), + passed + ) +} catch (e) { + recordCheck('Smallest valid input', 'Search/QuickSelectSearch.js:15', '[42], k=0', '[42]', e.message, false) +} + +// Boundary Check 2: Ordinary input (unsorted array, median k = 4) +try { + const input = [9, 2, 7, 4, 5, 6, 3, 8, 1] + const k = 4 + const expectedKVal = 5 + const actual = quickSelectSearch([...input], k) + const leftValid = actual.slice(0, 4).every(x => x <= expectedKVal) + const rightValid = actual.slice(5).every(x => x >= expectedKVal) + const passed = actual[4] === expectedKVal && leftValid && rightValid + recordCheck( + 'Ordinary input: 9 elements, target median k = 4', + 'Search/QuickSelectSearch.js:15', + '[9, 2, 7, 4, 5, 6, 3, 8, 1], k = 4', + 'result[4] === 5 with left <= 5 and right >= 5', + `result[4] = ${actual[4]}, array = ${JSON.stringify(actual)}`, + passed, + { leftValid, rightValid } + ) +} catch (e) { + recordCheck('Ordinary input', 'Search/QuickSelectSearch.js:15', '9 elements, k=4', '5 at index 4', e.message, false) +} + +// Boundary Check 3: Lower supported boundary (k = 0 on multi-element array) +try { + const input = [5, 1, 9, 3, 7] + const k = 0 + const actual = quickSelectSearch([...input], k) + const passed = actual[0] === 1 && actual.slice(1).every(x => x >= 1) + recordCheck( + 'Lower supported boundary: k = 0', + 'Search/QuickSelectSearch.js:15', + '[5, 1, 9, 3, 7], k = 0', + 'result[0] === 1 (minimum element)', + `result[0] = ${actual[0]}, array = ${JSON.stringify(actual)}`, + passed + ) +} catch (e) { + recordCheck('Lower supported boundary', 'Search/QuickSelectSearch.js:15', 'k=0', '1 at index 0', e.message, false) +} + +// Boundary Check 4: Upper supported boundary (k = array.length - 1) +try { + const input = [5, 1, 9, 3, 7] + const k = 4 // array.length - 1 + const actual = quickSelectSearch([...input], k) + const passed = actual[4] === 9 && actual.slice(0, 4).every(x => x <= 9) + recordCheck( + 'Upper supported boundary: k = array.length - 1', + 'Search/QuickSelectSearch.js:15', + '[5, 1, 9, 3, 7], k = 4', + 'result[4] === 9 (maximum element)', + `result[4] = ${actual[4]}, array = ${JSON.stringify(actual)}`, + passed + ) +} catch (e) { + recordCheck('Upper supported boundary', 'Search/QuickSelectSearch.js:15', 'k=4', '9 at index 4', e.message, false) +} + +// Boundary Check 5: Duplicate elements domain boundary +try { + const input = [3, 1, 3, 2, 3] + const k = 2 + const actual = quickSelectSearch([...input], k) + const passed = actual[2] === 3 + recordCheck( + 'Domain boundary: duplicate elements', + 'Search/QuickSelectSearch.js:15', + '[3, 1, 3, 2, 3], k = 2', + 'result[2] === 3', + `result[2] = ${actual[2]}, array = ${JSON.stringify(actual)}`, + passed + ) +} catch (e) { + recordCheck('Duplicate elements boundary', 'Search/QuickSelectSearch.js:15', '[3,1,3,2,3], k=2', '3 at index 2', e.message, false) +} + +// Boundary Check 6 (Unsupported): k equals array.length (just beyond upper boundary) +try { + quickSelectSearch([10, 20, 30], 3) + recordCheck('Unsupported boundary: k === array.length', 'Search/QuickSelectSearch.js:15', '[10, 20, 30], k = 3', 'throw Error("Invalid arguments")', 'No error thrown', false) +} catch (e) { + const passed = e.message === 'Invalid arguments' + recordCheck( + 'Unsupported boundary: k === array.length', + 'Search/QuickSelectSearch.js:15-16', + '[10, 20, 30], k = 3', + 'throw Error("Invalid arguments")', + `threw Error("${e.message}")`, + passed + ) +} + +// Boundary Check 7 (Unsupported): k exceeds array.length +try { + quickSelectSearch([10, 20, 30], 5) + recordCheck('Unsupported boundary: k > array.length', 'Search/QuickSelectSearch.js:15', '[10, 20, 30], k = 5', 'throw Error("Invalid arguments")', 'No error thrown', false) +} catch (e) { + const passed = e.message === 'Invalid arguments' + recordCheck( + 'Unsupported boundary: k > array.length', + 'Search/QuickSelectSearch.js:15-16', + '[10, 20, 30], k = 5', + 'throw Error("Invalid arguments")', + `threw Error("${e.message}")`, + passed + ) +} + +// Boundary Check 8 (Unsupported): Empty array +try { + quickSelectSearch([], 0) + recordCheck('Unsupported boundary: empty array', 'Search/QuickSelectSearch.js:15', '[], k = 0', 'throw Error("Invalid arguments")', 'No error thrown', false) +} catch (e) { + const passed = e.message === 'Invalid arguments' + recordCheck( + 'Unsupported boundary: empty array', + 'Search/QuickSelectSearch.js:15-16', + '[], k = 0', + 'throw Error("Invalid arguments")', + `threw Error("${e.message}")`, + passed + ) +} + +// Boundary Check 9 (Unsupported): Falsy array (null) +try { + quickSelectSearch(null, 0) + recordCheck('Unsupported boundary: null array', 'Search/QuickSelectSearch.js:15', 'null, k = 0', 'throw Error("Invalid arguments")', 'No error thrown', false) +} catch (e) { + const passed = e.message === 'Invalid arguments' + recordCheck( + 'Unsupported boundary: null array', + 'Search/QuickSelectSearch.js:15-16', + 'null, k = 0', + 'throw Error("Invalid arguments")', + `threw Error("${e.message}")`, + passed + ) +} + +console.log(JSON.stringify(results)) +""" + + proc = subprocess.run( + ["node", "--input-type=module", "-e", js_code], + cwd=repo_root, + capture_output=True, + text=True, + env=env + ) + + if proc.returncode != 0: + return { + "allPassed": False, + "error": proc.stderr or proc.stdout, + "checks": [] + } + + try: + return json.loads(proc.stdout) + except Exception as e: + return { + "allPassed": False, + "error": f"Failed to parse JSON output: {str(e)}: {proc.stdout}", + "checks": [] + } + +def main(): + script_dir = os.path.dirname(os.path.abspath(__file__)) + repo_root = os.path.abspath(os.path.join(script_dir, "..", "..")) + + print("=== Running Task R50-T042 Automated Checks ===") + print(f"Repository Root: {repo_root}") + + # 1. Tool versions + tools = get_tool_versions(repo_root) + print("\n--- Tool Versions ---") + for k, v in tools.items(): + print(f" {k}: {v}") + + # 2. Native repository tests + print("\n--- Native Repository Tests ---") + native_res = run_native_tests(repo_root) + print(f" Command: {native_res['command']}") + print(f" Exit Code: {native_res['exit_code']}") + print(f" Passed: {native_res['passed']}") + print(f" Nonzero Test Count: {native_res['test_count']}") + + if not native_res["passed"] or native_res["test_count"] == 0: + print("\nERROR: Native repository tests failed or zero tests found.") + print(native_res["output"]) + sys.exit(1) + + # 3. Boundary contract checks citing source line 15 + print("\n--- Boundary Contract Checks (Citing Source Preconditions) ---") + boundary_res = run_boundary_contract_checks(repo_root) + for c in boundary_res.get("checks", []): + status = "PASS" if c["passed"] else "FAIL" + print(f" [{status}] {c['name']}") + print(f" Precondition Line: {c['precondition_source_line']}") + print(f" Input: {c['input']}") + print(f" Expected: {c['expected']}") + print(f" Actual: {c['actual']}") + + if not boundary_res.get("allPassed", False): + print("\nERROR: Boundary contract checks failed.") + sys.exit(1) + + # 4. Save results to work/R50-T042/results.json + results_payload = { + "task_id": "R50-T042", + "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "precondition_contract": { + "source_file": "Search/QuickSelectSearch.js", + "precondition_lines": "15-16", + "precondition_code": "if (!array || array.length <= k) { throw new Error('Invalid arguments') }" + }, + "tools": tools, + "native_tests": { + "command": native_res["command"], + "exit_code": native_res["exit_code"], + "passed": native_res["passed"], + "test_count": native_res["test_count"] + }, + "boundary_checks": boundary_res["checks"], + "all_passed": True + } + + results_path = os.path.join(script_dir, "results.json") + with open(results_path, "w") as f: + json.dump(results_payload, f, indent=2) + + # Prettier format results.json to avoid pre-commit hook failure + env = os.environ.copy() + if "/opt/homebrew/bin" not in env.get("PATH", ""): + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + subprocess.run(["npx", "prettier", results_path, "--write"], cwd=repo_root, capture_output=True, env=env) + + print(f"\nAll checks passed successfully!") + print(f"Results saved to: {results_path}") + sys.exit(0) + +if __name__ == "__main__": + main() diff --git a/work/R50-T042/results.json b/work/R50-T042/results.json new file mode 100644 index 0000000000..1fc8f9e871 --- /dev/null +++ b/work/R50-T042/results.json @@ -0,0 +1,109 @@ +{ + "task_id": "R50-T042", + "timestamp": "2026-11-22T06:17:07Z", + "precondition_contract": { + "source_file": "Search/QuickSelectSearch.js", + "precondition_lines": "15-16", + "precondition_code": "if (!array || array.length <= k) { throw new Error('Invalid arguments') }" + }, + "tools": { + "python": "3.15.2", + "node": "v26.13.1", + "npm": "11.20.0", + "git_branch": "student/e26b07f0827/R50-T042", + "git_commit": "5c39e87a9a31f279c60f830ad74a845e4788a517" + }, + "native_tests": { + "command": "npm test -- Search/test/QuickSelectSearch.test.js", + "exit_code": 0, + "passed": true, + "test_count": 10 + }, + "boundary_checks": [ + { + "name": "Smallest valid input (1-element array, k = 0)", + "precondition_source_line": "Search/QuickSelectSearch.js:15", + "input": "array = [42], k = 0", + "expected": "[42]", + "actual": "[42]", + "passed": true, + "details": {} + }, + { + "name": "Ordinary input: 9 elements, target median k = 4", + "precondition_source_line": "Search/QuickSelectSearch.js:15", + "input": "[9, 2, 7, 4, 5, 6, 3, 8, 1], k = 4", + "expected": "result[4] === 5 with left <= 5 and right >= 5", + "actual": "result[4] = 5, array = [1,2,3,4,5,7,6,9,8]", + "passed": true, + "details": { + "leftValid": true, + "rightValid": true + } + }, + { + "name": "Lower supported boundary: k = 0", + "precondition_source_line": "Search/QuickSelectSearch.js:15", + "input": "[5, 1, 9, 3, 7], k = 0", + "expected": "result[0] === 1 (minimum element)", + "actual": "result[0] = 1, array = [1,3,5,7,9]", + "passed": true, + "details": {} + }, + { + "name": "Upper supported boundary: k = array.length - 1", + "precondition_source_line": "Search/QuickSelectSearch.js:15", + "input": "[5, 1, 9, 3, 7], k = 4", + "expected": "result[4] === 9 (maximum element)", + "actual": "result[4] = 9, array = [5,1,7,3,9]", + "passed": true, + "details": {} + }, + { + "name": "Domain boundary: duplicate elements", + "precondition_source_line": "Search/QuickSelectSearch.js:15", + "input": "[3, 1, 3, 2, 3], k = 2", + "expected": "result[2] === 3", + "actual": "result[2] = 3, array = [1,2,3,3,3]", + "passed": true, + "details": {} + }, + { + "name": "Unsupported boundary: k === array.length", + "precondition_source_line": "Search/QuickSelectSearch.js:15-16", + "input": "[10, 20, 30], k = 3", + "expected": "throw Error(\"Invalid arguments\")", + "actual": "threw Error(\"Invalid arguments\")", + "passed": true, + "details": {} + }, + { + "name": "Unsupported boundary: k > array.length", + "precondition_source_line": "Search/QuickSelectSearch.js:15-16", + "input": "[10, 20, 30], k = 5", + "expected": "throw Error(\"Invalid arguments\")", + "actual": "threw Error(\"Invalid arguments\")", + "passed": true, + "details": {} + }, + { + "name": "Unsupported boundary: empty array", + "precondition_source_line": "Search/QuickSelectSearch.js:15-16", + "input": "[], k = 0", + "expected": "throw Error(\"Invalid arguments\")", + "actual": "threw Error(\"Invalid arguments\")", + "passed": true, + "details": {} + }, + { + "name": "Unsupported boundary: null array", + "precondition_source_line": "Search/QuickSelectSearch.js:15-16", + "input": "null, k = 0", + "expected": "throw Error(\"Invalid arguments\")", + "actual": "threw Error(\"Invalid arguments\")", + "passed": true, + "details": {} + } + ], + "all_passed": true +}