diff --git a/Maths/RowEchelon.js b/Maths/RowEchelon.js index c773bb80a9..e0459f6c76 100644 --- a/Maths/RowEchelon.js +++ b/Maths/RowEchelon.js @@ -29,17 +29,50 @@ // Set a tolerance value for floating-point comparisons const tolerance = 0.000001 -// Check if all the rows have same length of elements +/** + * Validates whether the given input is a valid two-dimensional rectangular matrix. + * + * Trace & Decisive State Transition: + * 1. Initial State: Validates outer structure. Input must be a non-empty array whose first row is an array. + * 2. Dimension Target: Establishes expected column count `numCols = matrix[0].length`. + * 3. Row Inspection & Decisive Transition: Iterates across row indices `i` (0 <= i < numRows). + * - Decisive failure: If any row `matrix[i]` is not an array or `matrix[i].length !== numCols`, + * the validation transitions immediately to `false` (early exit). + * - Decisive success: If every row matches `numCols`, the validation transitions to `true`. + * + * @param {any} matrix - Two-dimensional array candidate to validate. + * @returns {boolean} True if matrix is a valid rectangular 2D array; false otherwise. + * + * @example + * // Example 1: Small rectangular matrix (2 rows x 3 columns) + * // Input: [[1, 2, 3], [4, 5, 6]] + * // numCols = 3; row 0 length = 3; row 1 length = 3. + * // Output: true + * isMatrixValid([[1, 2, 3], [4, 5, 6]]) // => true + * + * @example + * // Example 2: 1x1 matrix (1 row x 1 column) + * // Input: [[42]] + * // numCols = 1; row 0 length = 1. + * // Output: true + * isMatrixValid([[42]]) // => true + * + * @example + * // Example 3: Zero-containing matrix (2 rows x 2 columns) + * // Input: [[0, 5], [0, 0]] + * // numCols = 2; row 0 length = 2; row 1 length = 2. + * // Output: true + * isMatrixValid([[0, 5], [0, 0]]) // => true + * + * @example + * // Example 4: Non-uniform / ragged matrix (decisive failure transition) + * // Input: [[1, 2], [3]] + * // numCols = 2; row 0 length = 2; row 1 length = 1 !== 2 (decisive transition -> false). + * // Output: false + * isMatrixValid([[1, 2], [3]]) // => false + */ const isMatrixValid = (matrix) => { - let numRows = matrix.length - let numCols = matrix[0].length - for (let i = 0; i < numRows; i++) { - if (numCols !== matrix[i].length) { - return false - } - } - - // Check for input other than a 2D matrix + // Check for input other than a non-empty 2D matrix if ( !Array.isArray(matrix) || matrix.length === 0 || @@ -47,6 +80,17 @@ const isMatrixValid = (matrix) => { ) { return false } + + const numRows = matrix.length + const numCols = matrix[0].length + + for (let i = 0; i < numRows; i++) { + // Decisive transition: any row length deviation marks the matrix as invalid + if (!Array.isArray(matrix[i]) || matrix[i].length !== numCols) { + return false + } + } + return true } @@ -147,4 +191,4 @@ const rowEchelon = (matrix) => { return result } -export { rowEchelon } +export { rowEchelon, isMatrixValid } diff --git a/Maths/test/RowEchelon.test.js b/Maths/test/RowEchelon.test.js index 5575bc6d39..2d375ff565 100644 --- a/Maths/test/RowEchelon.test.js +++ b/Maths/test/RowEchelon.test.js @@ -1,4 +1,4 @@ -import { rowEchelon } from '../RowEchelon' +import { rowEchelon, isMatrixValid } from '../RowEchelon' describe('Determinant', () => { const tolerance = 0.000001 test.each([ @@ -87,3 +87,117 @@ describe('Determinant', () => { expect(() => rowEchelon(matrix)).toThrowError(expected) }) }) + +describe('isMatrixValid', () => { + test('validates small rectangular matrix fixture', () => { + const rectangularMatrix = [ + [1, 2, 3], + [4, 5, 6] + ] + expect(isMatrixValid(rectangularMatrix)).toBe(true) + + const tallRectangularMatrix = [ + [1, 2], + [3, 4], + [5, 6] + ] + expect(isMatrixValid(tallRectangularMatrix)).toBe(true) + }) + + test('validates 1x1 matrix fixture', () => { + const singleElementMatrix = [[42]] + expect(isMatrixValid(singleElementMatrix)).toBe(true) + + const singleZeroMatrix = [[0]] + expect(isMatrixValid(singleZeroMatrix)).toBe(true) + }) + + test('validates zero-containing matrix fixture', () => { + const zeroContainingMatrix = [ + [0, 5], + [0, 0] + ] + expect(isMatrixValid(zeroContainingMatrix)).toBe(true) + + const allZeroRectangular = [ + [0, 0, 0], + [0, 0, 0] + ] + expect(isMatrixValid(allZeroRectangular)).toBe(true) + }) + + test('executes and asserts JSDoc documentation examples', () => { + // Example 1: Small rectangular matrix (2x3) + expect( + isMatrixValid([ + [1, 2, 3], + [4, 5, 6] + ]) + ).toBe(true) + + // Example 2: 1x1 matrix + expect(isMatrixValid([[42]])).toBe(true) + + // Example 3: Zero-containing matrix (2x2) + expect( + isMatrixValid([ + [0, 5], + [0, 0] + ]) + ).toBe(true) + + // Example 4: Non-uniform / ragged matrix (decisive failure transition) + expect(isMatrixValid([[1, 2], [3]])).toBe(false) + }) + + test('rejects ragged matrices (decisive row length transition)', () => { + expect( + isMatrixValid([ + [1, 2, 3], + [4, 5] + ]) + ).toBe(false) + expect( + isMatrixValid([ + [1, 2], + [3, 4, 5] + ]) + ).toBe(false) + }) + + test('rejects non-matrix inputs and empty structures', () => { + expect(isMatrixValid([])).toBe(false) + expect(isMatrixValid(null)).toBe(false) + expect(isMatrixValid(undefined)).toBe(false) + expect(isMatrixValid('not a matrix')).toBe(false) + expect(isMatrixValid(123)).toBe(false) + expect(isMatrixValid([1, 2, 3])).toBe(false) + expect(isMatrixValid([[1, 2], 'not an array'])).toBe(false) + }) + + test('works consistently with rowEchelon on valid fixtures', () => { + // 1x1 matrix in rowEchelon + expect(rowEchelon([[42]])).toEqual([[1]]) + + // Rectangular 2x3 matrix in rowEchelon + const rect = [ + [1, 2, 3], + [4, 5, 6] + ] + const rectResult = rowEchelon(rect) + expect(rectResult.length).toBe(2) + expect(rectResult[0].length).toBe(3) + expect(rectResult[0][0]).toBeCloseTo(1) + expect(rectResult[1][0]).toBeCloseTo(0) + + // Zero-containing matrix in rowEchelon + const zeroMat = [ + [0, 2], + [3, 0] + ] + const zeroResult = rowEchelon(zeroMat) + expect(zeroResult[0][0]).toBeCloseTo(1) + expect(zeroResult[1][0]).toBeCloseTo(0) + expect(zeroResult[1][1]).toBeCloseTo(1) + }) +}) diff --git a/work/R50-T047/check.py b/work/R50-T047/check.py new file mode 100644 index 0000000000..4a1c001d86 --- /dev/null +++ b/work/R50-T047/check.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +""" +Automated check runner for Task R50-T047: +Publish a runnable example for isMatrixValid (Maths/RowEchelon.js). + +Executes repository native tests, verifies assertions on fixtures +(small rectangular matrix, 1x1 matrix, zero-containing matrix, doc examples), +and writes results to work/R50-T047/results.json. +""" + +import json +import os +import re +import subprocess +import sys +from datetime import datetime, timezone + +WORKSPACE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +RESULTS_DIR = os.path.join(WORKSPACE_DIR, "work", "R50-T047") +RESULTS_PATH = os.path.join(RESULTS_DIR, "results.json") + +def get_tool_versions(): + versions = {} + # Python + versions["python"] = sys.version.split()[0] + + # Node + try: + out = subprocess.run(["node", "--version"], capture_output=True, text=True, check=True) + versions["node"] = out.stdout.strip() + except Exception as e: + versions["node"] = str(e) + + # npm + try: + out = subprocess.run(["npm", "--version"], capture_output=True, text=True, check=True) + versions["npm"] = out.stdout.strip() + except Exception as e: + versions["npm"] = str(e) + + # vitest + try: + out = subprocess.run(["npx", "vitest", "--version"], cwd=WORKSPACE_DIR, capture_output=True, text=True, check=True) + versions["vitest"] = out.stdout.strip() + except Exception as e: + versions["vitest"] = str(e) + + return versions + +def run_native_tests(): + cmd = ["npm", "test", "--", "Maths/test/RowEchelon.test.js"] + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + result = subprocess.run(cmd, cwd=WORKSPACE_DIR, capture_output=True, text=True, env=env) + + output = result.stdout + "\n" + result.stderr + + # Parse test count: e.g. "Tests 12 passed (12)" + tests_passed = 0 + match = re.search(r"Tests\s+(\d+)\s+passed", output) + if match: + tests_passed = int(match.group(1)) + + return { + "command": " ".join(cmd), + "exit_code": result.returncode, + "tests_passed": tests_passed, + "output": output + } + +def run_node_eval(): + node_script = """ + import { isMatrixValid, rowEchelon } from './Maths/RowEchelon.js'; + + const fixtures = [ + { + name: "small_rectangular_matrix_2x3", + input: [[1, 2, 3], [4, 5, 6]], + expected: true + }, + { + name: "small_rectangular_matrix_3x2", + input: [[1, 2], [3, 4], [5, 6]], + expected: true + }, + { + name: "1x1_matrix", + input: [[42]], + expected: true + }, + { + name: "1x1_matrix_zero", + input: [[0]], + expected: true + }, + { + name: "zero_containing_matrix_2x2", + input: [[0, 5], [0, 0]], + expected: true + }, + { + name: "zero_containing_matrix_all_zero_rectangular", + input: [[0, 0, 0], [0, 0, 0]], + expected: true + }, + { + name: "doc_example_rectangular_2x3", + input: [[1, 2, 3], [4, 5, 6]], + expected: true + }, + { + name: "doc_example_1x1", + input: [[42]], + expected: true + }, + { + name: "doc_example_zero_containing", + input: [[0, 5], [0, 0]], + expected: true + }, + { + name: "doc_example_ragged_rejection", + input: [[1, 2], [3]], + expected: false + }, + { + name: "ragged_matrix_deviation", + input: [[1, 2, 3], [4, 5]], + expected: false + }, + { + name: "empty_matrix", + input: [], + expected: false + }, + { + name: "row_echelon_1x1_transform", + input: [[42]], + expected: [[1]], + transform: true + } + ]; + + const results = fixtures.map(f => { + let actual; + if (f.transform) { + actual = rowEchelon(f.input); + } else { + actual = isMatrixValid(f.input); + } + return { + name: f.name, + input: f.input, + expected: f.expected, + actual: actual, + passed: JSON.stringify(actual) === JSON.stringify(f.expected) + }; + }); + + console.log(JSON.stringify(results)); + """ + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + res = subprocess.run(["node", "--input-type=module", "-e", node_script], + cwd=WORKSPACE_DIR, capture_output=True, text=True, env=env) + if res.returncode != 0: + raise RuntimeError(f"Node execution failed: {res.stderr}") + return json.loads(res.stdout.strip()) + +def main(): + print(f"Running checks for Task R50-T047...") + tool_versions = get_tool_versions() + native_test_result = run_native_tests() + + if native_test_result["exit_code"] != 0: + print(f"Native tests failed with exit code {native_test_result['exit_code']}") + print(native_test_result["output"]) + sys.exit(1) + + print(f"Native tests passed: {native_test_result['tests_passed']} tests.") + + assertion_results = run_node_eval() + all_passed = True + for item in assertion_results: + if not item["passed"]: + print(f"Assertion failed for {item['name']}: expected {item['expected']}, got {item['actual']}") + all_passed = False + else: + print(f" ✓ {item['name']}: passed") + + if not all_passed: + print("Some assertions failed.") + sys.exit(1) + + os.makedirs(RESULTS_DIR, exist_ok=True) + summary = { + "task_id": "R50-T047", + "target": "Maths/RowEchelon.js", + "tested_function": "isMatrixValid", + "timestamp": datetime.now(timezone.utc).isoformat(), + "tool_versions": tool_versions, + "native_test": { + "command": native_test_result["command"], + "exit_code": native_test_result["exit_code"], + "tests_passed": native_test_result["tests_passed"] + }, + "assertions": assertion_results, + "status": "PASSED" + } + + with open(RESULTS_PATH, "w") as f: + json.dump(summary, f, indent=2) + print(f"Results written to {RESULTS_PATH}") + + # Format with prettier to satisfy pre-commit hook + env = os.environ.copy() + env["PATH"] = f"/opt/homebrew/bin:{env.get('PATH', '')}" + subprocess.run(["npx", "prettier", RESULTS_PATH, "--write"], cwd=WORKSPACE_DIR, env=env, check=False) + print(f"Prettier formatting applied to {RESULTS_PATH}") + +if __name__ == "__main__": + main() diff --git a/work/R50-T047/results.json b/work/R50-T047/results.json new file mode 100644 index 0000000000..ec3542fc38 --- /dev/null +++ b/work/R50-T047/results.json @@ -0,0 +1,133 @@ +{ + "task_id": "R50-T047", + "target": "Maths/RowEchelon.js", + "tested_function": "isMatrixValid", + "timestamp": "2026-11-22T07:40:13.548616+00:00", + "tool_versions": { + "python": "3.15.2", + "node": "v26.13.1", + "npm": "11.20.0", + "vitest": "vitest/1.2.1 darwin-arm64 node-v26.13.1" + }, + "native_test": { + "command": "npm test -- Maths/test/RowEchelon.test.js", + "exit_code": 0, + "tests_passed": 12 + }, + "assertions": [ + { + "name": "small_rectangular_matrix_2x3", + "input": [ + [1, 2, 3], + [4, 5, 6] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "small_rectangular_matrix_3x2", + "input": [ + [1, 2], + [3, 4], + [5, 6] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "1x1_matrix", + "input": [[42]], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "1x1_matrix_zero", + "input": [[0]], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "zero_containing_matrix_2x2", + "input": [ + [0, 5], + [0, 0] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "zero_containing_matrix_all_zero_rectangular", + "input": [ + [0, 0, 0], + [0, 0, 0] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "doc_example_rectangular_2x3", + "input": [ + [1, 2, 3], + [4, 5, 6] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "doc_example_1x1", + "input": [[42]], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "doc_example_zero_containing", + "input": [ + [0, 5], + [0, 0] + ], + "expected": true, + "actual": true, + "passed": true + }, + { + "name": "doc_example_ragged_rejection", + "input": [[1, 2], [3]], + "expected": false, + "actual": false, + "passed": true + }, + { + "name": "ragged_matrix_deviation", + "input": [ + [1, 2, 3], + [4, 5] + ], + "expected": false, + "actual": false, + "passed": true + }, + { + "name": "empty_matrix", + "input": [], + "expected": false, + "actual": false, + "passed": true + }, + { + "name": "row_echelon_1x1_transform", + "input": [[1]], + "expected": [[1]], + "actual": [[1]], + "passed": true + } + ], + "status": "PASSED" +}