diff --git a/2025.03.07/1Ex/main.c b/2025.03.07/1Ex/main.c index 12ed985..8727dd5 100644 --- a/2025.03.07/1Ex/main.c +++ b/2025.03.07/1Ex/main.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) k >= 0 && k <= 4 && (!(k == 0 && argc != 5)))) { printf("Usage: %s n p k [filename]\n", argv[0]); - return 0; + return 1; } if (argc == 5) name = argv[4]; diff --git a/2025.03.07/2Ex/main.c b/2025.03.07/2Ex/main.c index 13e5a6f..a501808 100644 --- a/2025.03.07/2Ex/main.c +++ b/2025.03.07/2Ex/main.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) k >= 0 && k <= 4 && (!(k == 0 && argc != 5)))) { printf("Usage: %s n p k [filename]\n", argv[0]); - return 0; + return 1; } if (argc == 5) name = argv[4]; diff --git a/2025.03.07/3Ex/main.c b/2025.03.07/3Ex/main.c index 2828326..d80c184 100644 --- a/2025.03.07/3Ex/main.c +++ b/2025.03.07/3Ex/main.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) k >= 0 && k <= 4 && (!(k == 0 && argc != 5)))) { printf("Usage: %s n p k [filename]\n", argv[0]); - return 0; + return 1; } if (argc == 5) name = argv[4]; diff --git a/2025.03.07/4Ex/main.c b/2025.03.07/4Ex/main.c index 2b0381b..993a790 100644 --- a/2025.03.07/4Ex/main.c +++ b/2025.03.07/4Ex/main.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) k >= 0 && k <= 4 && (!(k == 0 && argc != 5)))) { printf("Usage: %s n p k [filename]\n", argv[0]); - return 0; + return 1; } if (argc == 5) name = argv[4]; diff --git a/2025.03.07/5Ex/main.c b/2025.03.07/5Ex/main.c index 7427c9c..cb8dd78 100644 --- a/2025.03.07/5Ex/main.c +++ b/2025.03.07/5Ex/main.c @@ -19,7 +19,7 @@ int main(int argc, char *argv[]) k >= 0 && k <= 4 && (!(k == 0 && argc != 5)))) { printf("Usage: %s n p k [filename]\n", argv[0]); - return 0; + return 1; } if (argc == 5) name = argv[4]; diff --git a/2025.03.07/6Ex/Makefile b/2025.03.07/6Ex/Makefile new file mode 100644 index 0000000..0757921 --- /dev/null +++ b/2025.03.07/6Ex/Makefile @@ -0,0 +1,19 @@ +FLAGS = -fstack-protector-all -W -Wall -Wextra -Wunused -Wcast-align -Werror -pedantic -pedantic-errors -Wfloat-equal -Wpointer-arith -Wformat-security -Wmissing-format-attribute -Wformat=1 -Wwrite-strings -Wcast-align -Wno-long-long -std=gnu99 -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -Wdeclaration-after-statement -Wbad-function-cast -Wnested-externs -O3 + +a06.exe: main.o array_io.o solve.o init_f.o + gcc main.o solve.o array_io.o init_f.o -o a06.exe -lssp + +main.o: main.c + gcc $(CFLAGS) -c main.c + +solve.o: solve.c + gcc $(FLAGS) -c solve.c + +array_io.o: array_io.c + gcc $(CFLAGS) -c array_io.c + +init_f.o: init_f.c + gcc $(CFLAGS) -c init_f.c + +clean: + del *.o *.exe diff --git a/2025.03.07/6Ex/array_io.c b/2025.03.07/6Ex/array_io.c new file mode 100644 index 0000000..6e56ecf --- /dev/null +++ b/2025.03.07/6Ex/array_io.c @@ -0,0 +1,40 @@ +#include +#include "array_io.h" + +io_status read_matrix(double *a, int n, int m, const char *name) +{ + int i, j; + FILE *fp; + if (!(fp = fopen(name, "r"))) return ERROR_OPEN; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + if (fscanf(fp, "%lf", a + i * m + j) != 1) + {fclose(fp); return ERROR_READ;} + fclose(fp); + return SUCCESS; +} + +void print_matrix(const double *a, int n, int m, int p) +{ + int np = (n > p ? p : n); + int mp = (m > p ? p : m); + int i, j; + + for (i = 0; i < np; i++) + { + for (j = 0; j < mp; j++) + printf(" %10.3e", a[i * m + j]); + printf("\n"); + } +} + +void init_matrix(double *a, int n, int m, int k) +{ + double (*q)(int, int, int, int); + double (*f[])(int, int, int, int) = {f1, f2, f3, f4}; + int i, j; + q = f[k-1]; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + a[i * m + j] = q(n, m, i+1, j+1); +} diff --git a/2025.03.07/6Ex/array_io.h b/2025.03.07/6Ex/array_io.h new file mode 100644 index 0000000..e312a84 --- /dev/null +++ b/2025.03.07/6Ex/array_io.h @@ -0,0 +1,11 @@ +#ifndef ARRAY_IO_H +#define ARRAY_IO_H + +#include "io_status.h" +#include "init_f.h" + +io_status read_matrix(double *a, int n, int m, const char *name); +void print_matrix(const double *a, int n, int m, int p); +void init_matrix(double *a, int n, int m, int k); + +#endif diff --git a/2025.03.07/6Ex/init_f.c b/2025.03.07/6Ex/init_f.c new file mode 100644 index 0000000..cf325c3 --- /dev/null +++ b/2025.03.07/6Ex/init_f.c @@ -0,0 +1,30 @@ +#include "init_f.h" +#include + +#define MAX(n, m) (n < m ? m : n) + +double f1(int n, int m, int i, int j) +{ + return MAX(n, m) - MAX(i, j) + 1; +} + +double f2(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return MAX(i, j); +} + +double f3(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return abs(i - j); +} + +double f4(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return 1./(i+j-1); +} diff --git a/2025.03.07/6Ex/init_f.h b/2025.03.07/6Ex/init_f.h new file mode 100644 index 0000000..691aace --- /dev/null +++ b/2025.03.07/6Ex/init_f.h @@ -0,0 +1,9 @@ +#ifndef INIT_F_H +#define INIT_F_H + +double f1(int n, int m, int i, int j); +double f2(int n, int m, int i, int j); +double f3(int n, int m, int i, int j); +double f4(int n, int m, int i, int j); + +#endif diff --git a/2025.03.07/6Ex/io_status.h b/2025.03.07/6Ex/io_status.h new file mode 100644 index 0000000..a51376d --- /dev/null +++ b/2025.03.07/6Ex/io_status.h @@ -0,0 +1,14 @@ +#ifndef IO_STATUS_H +#define IO_STATUS_H + +#define LEN 1234 + +typedef enum _io_status +{ + SUCCESS, + ERROR_OPEN, + ERROR_READ, + ERROR_MEM +} io_status; + +#endif diff --git a/2025.03.07/6Ex/main.c b/2025.03.07/6Ex/main.c new file mode 100644 index 0000000..9fe5a8f --- /dev/null +++ b/2025.03.07/6Ex/main.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include "array_io.h" +#include "io_status.h" +#include "solve.h" + +/* ./a.out i j n m p k [filename] */ +int main(int argc, char *argv[]) +{ + double t, res, *a; + int i, j, n, m, p, k, task = 6; + char *name = 0; + + if (!((argc == 7 || argc == 8) && + sscanf(argv[1], "%d", &i) == 1 && + sscanf(argv[2], "%d", &j) == 1 && + sscanf(argv[3], "%d", &n) == 1 && + sscanf(argv[4], "%d", &m) == 1 && + sscanf(argv[5], "%d", &p) == 1 && + sscanf(argv[6], "%d", &k) == 1 && + k >= 0 && k <= 4 && (!(k == 0 && argc != 8)) && + (i <= n && j <= m) && (i > 0 && j > 0))) + { + printf("Usage: %s i j n m p k [filename]\n", argv[0]); + return 1; + } + if (argc == 8) name = argv[7]; + + a = (double *)malloc(n * m * sizeof(double)); + if (!a) + { + printf("Not enough memory\n"); + return 2; + } + + if (name) + { /* из файла */ + io_status ret; + ret = read_matrix(a, n, m, name); + do { + switch (ret) + { + case SUCCESS: + continue; + case ERROR_OPEN: + printf("Cannot open %s\n", name); + break; + case ERROR_READ: + printf("Cannot read %s\n", name); + } + free(a); + return 3; + } while (0); + } else init_matrix(a, n, m, k); + + printf("Initial matrix:\n"); + print_matrix(a, n, m, p); + + t = clock(); + t6_solve(a, n, m, i-1, j-1); + t = (clock() - t) / CLOCKS_PER_SEC; + + printf("Result matrix:\n"); + print_matrix(a, n, m, p); + printf("%s : Task = %d Elapsed = %.2f\n", argv[0], task, t); + free(a); + return 0; +} diff --git a/2025.03.07/6Ex/solve.c b/2025.03.07/6Ex/solve.c new file mode 100644 index 0000000..7ff3722 --- /dev/null +++ b/2025.03.07/6Ex/solve.c @@ -0,0 +1,15 @@ +#include "solve.h" +#include "math.h" + +void t6_solve(double *a, int n, int m, int i, int j) +{ + double temp; + int k; + (void)n; + for (k = 0; k < m; k++) + { + temp = a[i * m + k]; + a[i * m + k] = a[j * m + k]; + a[j * m + k] = temp; + } +} diff --git a/2025.03.07/6Ex/solve.h b/2025.03.07/6Ex/solve.h new file mode 100644 index 0000000..369ff04 --- /dev/null +++ b/2025.03.07/6Ex/solve.h @@ -0,0 +1,6 @@ +#ifndef SOLVE_H +#define SOLVE_H + +void t6_solve(double *a, int n, int m, int i, int j); + +#endif diff --git a/2025.03.07/6Ex/t.txt b/2025.03.07/6Ex/t.txt new file mode 100644 index 0000000..65c2e7c --- /dev/null +++ b/2025.03.07/6Ex/t.txt @@ -0,0 +1,5 @@ +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 +17 18 19 20 diff --git a/2025.03.07/6Ex/test_cases.json b/2025.03.07/6Ex/test_cases.json new file mode 100644 index 0000000..99d4f67 --- /dev/null +++ b/2025.03.07/6Ex/test_cases.json @@ -0,0 +1,110 @@ +{ + "exe": "a06.exe", + "filename": "matrix.txt", + "tests": [ + { + "name": "File Matrix Test", + "i": 1, + "j": 2, + "k": 0, + "matrix": "1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n17 18 19 20" + }, + { + "name": "Basic Row Swap", + "i": 1, + "j": 2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "2x2 Swap", + "i": 1, + "j": 2, + "n": 2, + "m": 2, + "p": 2, + "k": 0, + "matrix": "10 20\n30 40" + }, + { + "name": "Large 1000x1000 Matrix", + "i": 500, + "j": 999, + "n": 1000, + "m": 1000, + "p": 999, + "k": 1 + }, + { + "name": "Floating Point Values", + "i": 1, + "j": 3, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1.1 2.2 3.3\n4.4 5.5 6.6\n7.7 8.8 9.9" + }, + { + "name": "Negative Values", + "i": 1, + "j": 2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "-1 -2 -3\n-4 -5 -6\n-7 -8 -9" + }, + { + "name": "Randomized Matrix", + "i": 3, + "j": 5, + "n": 6, + "m": 6, + "k": 0, + "matrix": "2 4 6 8 10 12\n14 16 18 20 22 24\n26 28 30 32 34 36\n38 40 42 44 46 48\n50 52 54 56 58 60\n62 64 66 68 70 72" + }, + { + "name": "Identity Matrix", + "i": 2, + "j": 3, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 0 0\n0 1 0\n0 0 1" + }, + { + "name": "All Zeroes", + "i": 1, + "j": 2, + "n": 4, + "m": 4, + "p": 4, + "k": 0, + "matrix": "0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0" + }, + { + "name": "Row Swap Itself", + "i": 1, + "j": 1, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Different Row Sizes", + "i": 2, + "j": 3, + "n": 4, + "m": 5, + "k": 0, + "matrix": "10 20 30 40 50\n60 70 80 90 100\n110 120 130 140 150\n160 170 180 190 200" + } + ] +} diff --git a/2025.03.07/6Ex/test_runner.py b/2025.03.07/6Ex/test_runner.py new file mode 100644 index 0000000..52fe6d9 --- /dev/null +++ b/2025.03.07/6Ex/test_runner.py @@ -0,0 +1,175 @@ +import json +import subprocess +import os +import time +import platform +import re +import signal +from colorama import Fore, Style, init + +# Enable color support in Windows +init(autoreset=True) + +def color_text(text, color): + """Returns colored text""" + return color + text + Style.RESET_ALL + +def cleanup_and_exit(): + """Handles cleanup on Ctrl+C or forced exit""" + print(color_text("\n[ABORT] Operation interrupted. Cleaning up...", Fore.RED)) + run_command("make clean") + exit(1) + +# Register Ctrl+C handler +signal.signal(signal.SIGINT, lambda sig, frame: cleanup_and_exit()) + +class TestCase: + """Represents a single test case""" + def __init__(self, i, j, k, matrix=None, n=None, m=None, p=None, debug=False, name=None): + self.i = i + self.j = j + self.k = k + self.matrix = matrix + self.n = n + self.m = m + self.p = p + self.debug = debug + self.name = name if name else f"Test k={k}, n={n if n else 'auto'}, m={m if m else 'auto'}, p={p if p else 'auto'}" + + # Compute `n` if missing and `k == 0` + if self.k == 0 and self.matrix: + if not self.n: + self.n = len(self.matrix.strip().split("\n")) + if not self.m: + self.m = len(self.matrix.strip().split("\n")[0].split()) + + # Compute `p` + self.p = self.p if self.p else self.n + + def validate_inputs(self): + """Ensures input values are valid""" + if self.k < 0 or (self.k == 0 and not self.matrix): + print(color_text(f"[ERROR] Invalid test parameters: {self.name}", Fore.RED)) + return False + return True + +class TestSuite: + """Handles loading and running test cases""" + def __init__(self, config_file): + self.config = self.load_config(config_file) + self.exe = self.config["exe"] + self.filename = self.config["filename"] + self.tests = [TestCase(**test) for test in self.config["tests"]] + + @staticmethod + def load_config(filename): + """Loads test cases from JSON""" + with open(filename, "r", encoding="utf-8") as f: + return json.load(f) + +def run_command(cmd, exit_on_error=False): + """Runs a shell command and handles errors""" + try: + result = subprocess.run(cmd, shell=True, capture_output=True, text=True) + return result + except subprocess.CalledProcessError as e: + print(color_text(f"[ERROR] Command failed: {cmd}", Fore.RED)) + print(e.stderr) + if exit_on_error: + exit(1) + return None + +def wait_for_executable(exe): + """Waits for the executable file to appear after compilation""" + print(color_text(f"[WAIT] Waiting for {exe} to be compiled...", Fore.YELLOW)) + while not os.path.exists(exe): + time.sleep(0.1) # Reduce CPU usage + print(color_text(f"[READY] {exe} compiled successfully.", Fore.GREEN)) + +def format_matrix(matrix): + """Formats a matrix to match `printf("%10.3e")` output""" + formatted = [] + for row in matrix.strip().split("\n"): + formatted.append(" ".join(f"{float(num):10.3e}" for num in row.split())) + return "\n".join(formatted) + +def result_matrix_output(output): + parts = output.split("Result matrix:\n") + if len(parts) > 1: + matrix_lines = parts[1].strip().split("\n") + return format_matrix("\n".join(matrix_lines[:-1])) + return "" + +def initial_matrix_output(output): + parts = output.split("Initial matrix:\n") + if len(parts) > 1: + parts = parts[1].split("Result") + matrix_lines = parts[0].strip().split("\n") + return format_matrix("\n".join(matrix_lines)) + return "" + +def ep2_matrix(matrix, i, j): + rows = matrix.strip().split("\n") + rows[i-1], rows[j-1] = rows[j-1], rows[i-1] + ep2 = [row.split() for row in rows] + return "\n".join(" ".join(f"{float(num):10.3e}" for num in row) for row in ep2) + +def run_test(test_suite, test): + """Runs the program and checks its result""" + if not test.validate_inputs(): + return + + exe, filename = test_suite.exe, test_suite.filename + + # If matrix is given, write it to the file + if test.k == 0 and test.matrix: + with open(filename, "w", encoding="utf-8") as f: + f.write(format_matrix(test.matrix.strip()) + "\n") + + cmd = [exe, str(test.i), str(test.j), str(test.n), str(test.m), str(test.p), str(test.k)] + if test.k == 0: + cmd.append(filename) + + # Run the program + result = run_command(cmd) + + # Extract both initial and result matrices + initial_matrix = initial_matrix_output(result.stdout) + result_matrix = result_matrix_output(result.stdout) + + expected_transposed = ep2_matrix(initial_matrix, test.i, test.j) + + if result_matrix.strip() != expected_transposed.strip(): + print(color_text(f"[FAIL] Test '{test.name}' matrix mismatch.", Fore.RED)) + print(f"Expected:\n{expected_transposed}") + print(f"Got:\n{result_matrix}") + return + + print(color_text(f"[PASS] Test '{test.name}' passed.", Fore.GREEN)) + + if test.k == 0: + # Cleanup test file + try: + os.remove(filename) + except (FileNotFoundError, PermissionError): + print(color_text(f"[WARNING] Could not delete {filename}, Windows may be locking it.", Fore.RED)) + + +def main(): + print(color_text("[CLEAN] Cleaning project...", Fore.BLUE)) + run_command("make clean", exit_on_error=True) + + print(color_text("[BUILD] Compiling project...", Fore.BLUE)) + run_command("make", exit_on_error=True) + + test_suite = TestSuite("test_cases.json") + wait_for_executable(test_suite.exe) + + for test in test_suite.tests: + run_test(test_suite, test) + + print(color_text("[CLEAN] Final cleanup...", Fore.BLUE)) + run_command("make clean") + +if __name__ == "__main__": + main() diff --git a/2025.03.07/7Ex/Makefile b/2025.03.07/7Ex/Makefile new file mode 100644 index 0000000..f959ca4 --- /dev/null +++ b/2025.03.07/7Ex/Makefile @@ -0,0 +1,19 @@ +FLAGS = -fstack-protector-all -W -Wall -Wextra -Wunused -Wcast-align -Werror -pedantic -pedantic-errors -Wfloat-equal -Wpointer-arith -Wformat-security -Wmissing-format-attribute -Wformat=1 -Wwrite-strings -Wcast-align -Wno-long-long -std=gnu99 -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -Wdeclaration-after-statement -Wbad-function-cast -Wnested-externs -O3 + +a07.exe: main.o array_io.o solve.o init_f.o + gcc main.o solve.o array_io.o init_f.o -o a07.exe -lssp + +main.o: main.c + gcc $(CFLAGS) -c main.c + +solve.o: solve.c + gcc $(FLAGS) -c solve.c + +array_io.o: array_io.c + gcc $(CFLAGS) -c array_io.c + +init_f.o: init_f.c + gcc $(CFLAGS) -c init_f.c + +clean: + del *.o *.exe diff --git a/2025.03.07/7Ex/array_io.c b/2025.03.07/7Ex/array_io.c new file mode 100644 index 0000000..6e56ecf --- /dev/null +++ b/2025.03.07/7Ex/array_io.c @@ -0,0 +1,40 @@ +#include +#include "array_io.h" + +io_status read_matrix(double *a, int n, int m, const char *name) +{ + int i, j; + FILE *fp; + if (!(fp = fopen(name, "r"))) return ERROR_OPEN; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + if (fscanf(fp, "%lf", a + i * m + j) != 1) + {fclose(fp); return ERROR_READ;} + fclose(fp); + return SUCCESS; +} + +void print_matrix(const double *a, int n, int m, int p) +{ + int np = (n > p ? p : n); + int mp = (m > p ? p : m); + int i, j; + + for (i = 0; i < np; i++) + { + for (j = 0; j < mp; j++) + printf(" %10.3e", a[i * m + j]); + printf("\n"); + } +} + +void init_matrix(double *a, int n, int m, int k) +{ + double (*q)(int, int, int, int); + double (*f[])(int, int, int, int) = {f1, f2, f3, f4}; + int i, j; + q = f[k-1]; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + a[i * m + j] = q(n, m, i+1, j+1); +} diff --git a/2025.03.07/7Ex/array_io.h b/2025.03.07/7Ex/array_io.h new file mode 100644 index 0000000..e312a84 --- /dev/null +++ b/2025.03.07/7Ex/array_io.h @@ -0,0 +1,11 @@ +#ifndef ARRAY_IO_H +#define ARRAY_IO_H + +#include "io_status.h" +#include "init_f.h" + +io_status read_matrix(double *a, int n, int m, const char *name); +void print_matrix(const double *a, int n, int m, int p); +void init_matrix(double *a, int n, int m, int k); + +#endif diff --git a/2025.03.07/7Ex/init_f.c b/2025.03.07/7Ex/init_f.c new file mode 100644 index 0000000..cf325c3 --- /dev/null +++ b/2025.03.07/7Ex/init_f.c @@ -0,0 +1,30 @@ +#include "init_f.h" +#include + +#define MAX(n, m) (n < m ? m : n) + +double f1(int n, int m, int i, int j) +{ + return MAX(n, m) - MAX(i, j) + 1; +} + +double f2(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return MAX(i, j); +} + +double f3(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return abs(i - j); +} + +double f4(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return 1./(i+j-1); +} diff --git a/2025.03.07/7Ex/init_f.h b/2025.03.07/7Ex/init_f.h new file mode 100644 index 0000000..691aace --- /dev/null +++ b/2025.03.07/7Ex/init_f.h @@ -0,0 +1,9 @@ +#ifndef INIT_F_H +#define INIT_F_H + +double f1(int n, int m, int i, int j); +double f2(int n, int m, int i, int j); +double f3(int n, int m, int i, int j); +double f4(int n, int m, int i, int j); + +#endif diff --git a/2025.03.07/7Ex/io_status.h b/2025.03.07/7Ex/io_status.h new file mode 100644 index 0000000..a51376d --- /dev/null +++ b/2025.03.07/7Ex/io_status.h @@ -0,0 +1,14 @@ +#ifndef IO_STATUS_H +#define IO_STATUS_H + +#define LEN 1234 + +typedef enum _io_status +{ + SUCCESS, + ERROR_OPEN, + ERROR_READ, + ERROR_MEM +} io_status; + +#endif diff --git a/2025.03.07/7Ex/main.c b/2025.03.07/7Ex/main.c new file mode 100644 index 0000000..325f879 --- /dev/null +++ b/2025.03.07/7Ex/main.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include "array_io.h" +#include "io_status.h" +#include "solve.h" + +/* ./a.out i j n m p k [filename] */ +int main(int argc, char *argv[]) +{ + double t, res, *a; + int i, j, n, m, p, k, task = 7; + char *name = 0; + + if (!((argc == 7 || argc == 8) && + sscanf(argv[1], "%d", &i) == 1 && + sscanf(argv[2], "%d", &j) == 1 && + sscanf(argv[3], "%d", &n) == 1 && + sscanf(argv[4], "%d", &m) == 1 && + sscanf(argv[5], "%d", &p) == 1 && + sscanf(argv[6], "%d", &k) == 1 && + k >= 0 && k <= 4 && (!(k == 0 && argc != 8)) && + (i <= n && j <= m) && (i > 0 && j > 0))) + { + printf("Usage: %s i j n m p k [filename]\n", argv[0]); + return 1; + } + if (argc == 8) name = argv[7]; + + a = (double *)malloc(n * m * sizeof(double)); + if (!a) + { + printf("Not enough memory\n"); + return 2; + } + + if (name) + { /* из файла */ + io_status ret; + ret = read_matrix(a, n, m, name); + do { + switch (ret) + { + case SUCCESS: + continue; + case ERROR_OPEN: + printf("Cannot open %s\n", name); + break; + case ERROR_READ: + printf("Cannot read %s\n", name); + } + free(a); + return 3; + } while (0); + } else init_matrix(a, n, m, k); + + printf("Initial matrix:\n"); + print_matrix(a, n, m, p); + + t = clock(); + t7_solve(a, n, m, i-1, j-1); + t = (clock() - t) / CLOCKS_PER_SEC; + + printf("Result matrix:\n"); + print_matrix(a, n, m, p); + printf("%s : Task = %d Elapsed = %.2f\n", argv[0], task, t); + free(a); + return 0; +} diff --git a/2025.03.07/7Ex/solve.c b/2025.03.07/7Ex/solve.c new file mode 100644 index 0000000..e016c5c --- /dev/null +++ b/2025.03.07/7Ex/solve.c @@ -0,0 +1,14 @@ +#include "solve.h" +#include "math.h" + +void t7_solve(double *a, int n, int m, int i, int j) +{ + double temp; + int k; + for (k = 0; k < n; k++) + { + temp = a[k * m + i]; + a[k * m + i] = a[k * m + j]; + a[k * m + j] = temp; + } +} diff --git a/2025.03.07/7Ex/solve.h b/2025.03.07/7Ex/solve.h new file mode 100644 index 0000000..0198ab8 --- /dev/null +++ b/2025.03.07/7Ex/solve.h @@ -0,0 +1,6 @@ +#ifndef SOLVE_H +#define SOLVE_H + +void t7_solve(double *a, int n, int m, int i, int j); + +#endif diff --git a/2025.03.07/7Ex/t.txt b/2025.03.07/7Ex/t.txt new file mode 100644 index 0000000..65c2e7c --- /dev/null +++ b/2025.03.07/7Ex/t.txt @@ -0,0 +1,5 @@ +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 +17 18 19 20 diff --git a/2025.03.07/7Ex/test_cases.json b/2025.03.07/7Ex/test_cases.json new file mode 100644 index 0000000..8337f2c --- /dev/null +++ b/2025.03.07/7Ex/test_cases.json @@ -0,0 +1,118 @@ +{ + "exe": "a07.exe", + "filename": "matrix.txt", + "tests": [ + { + "name": "File Matrix Test", + "i": 1, + "j": 2, + "k": 0, + "matrix": "1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n17 18 19 20" + }, + { + "name": "i equal j", + "i": 1, + "j": 1, + "n": 5, + "m": 10, + "k": 1 + }, + { + "name": "Basic Row Swap", + "i": 1, + "j": 2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "2x2 Swap", + "i": 1, + "j": 2, + "n": 2, + "m": 2, + "p": 2, + "k": 0, + "matrix": "10 20\n30 40" + }, + { + "name": "Large 1000x1000 Matrix", + "i": 500, + "j": 999, + "n": 1000, + "m": 1000, + "p": 999, + "k": 1 + }, + { + "name": "Floating Point Values", + "i": 1, + "j": 3, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1.1 2.2 3.3\n4.4 5.5 6.6\n7.7 8.8 9.9" + }, + { + "name": "Negative Values", + "i": 1, + "j": 2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "-1 -2 -3\n-4 -5 -6\n-7 -8 -9" + }, + { + "name": "Randomized Matrix", + "i": 3, + "j": 5, + "n": 6, + "m": 6, + "k": 0, + "matrix": "2 4 6 8 10 12\n14 16 18 20 22 24\n26 28 30 32 34 36\n38 40 42 44 46 48\n50 52 54 56 58 60\n62 64 66 68 70 72" + }, + { + "name": "Identity Matrix", + "i": 2, + "j": 3, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 0 0\n0 1 0\n0 0 1" + }, + { + "name": "All Zeroes", + "i": 1, + "j": 2, + "n": 4, + "m": 4, + "p": 4, + "k": 0, + "matrix": "0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0" + }, + { + "name": "Row Swap Itself", + "i": 1, + "j": 1, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Different Row Sizes", + "i": 2, + "j": 3, + "n": 4, + "m": 5, + "k": 0, + "matrix": "10 20 30 40 50\n60 70 80 90 100\n110 120 130 140 150\n160 170 180 190 200" + } + ] +} diff --git a/2025.03.07/7Ex/test_runner.py b/2025.03.07/7Ex/test_runner.py new file mode 100644 index 0000000..57cd1e5 --- /dev/null +++ b/2025.03.07/7Ex/test_runner.py @@ -0,0 +1,206 @@ +import json +import subprocess +import os +import time +import platform +import re +import signal +from colorama import Fore, Style, init + +# Enable color support in Windows +init(autoreset=True) + +def color_text(text, color): + """Returns colored text""" + return color + text + Style.RESET_ALL + +def cleanup_and_exit(): + """Handles cleanup on Ctrl+C or forced exit""" + print(color_text("\n[ABORT] Operation interrupted. Cleaning up...", Fore.RED)) + run_command("make clean") + exit(1) + +# Register Ctrl+C handler +signal.signal(signal.SIGINT, lambda sig, frame: cleanup_and_exit()) + +class TestCase: + """Represents a single test case""" + def __init__(self, i, j, k, matrix=None, n=None, m=None, p=None, debug=False, name=None): + self.i = i + self.j = j + self.k = k + self.matrix = matrix + self.n = n + self.m = m + self.p = p + self.debug = debug + self.name = name if name else f"Test k={k}, n={n if n else 'auto'}, m={m if m else 'auto'}, p={p if p else 'auto'}" + + # Compute `n` if missing and `k == 0` + if self.k == 0 and self.matrix: + if not self.n: + self.n = len(self.matrix.strip().split("\n")) + if not self.m: + self.m = len(self.matrix.strip().split("\n")[0].split()) + + # Compute `p` + self.p = self.p if self.p else self.n + + def validate_inputs(self): + """Ensures input values are valid""" + if self.k < 0 or (self.k == 0 and not self.matrix): + print(color_text(f"[ERROR] Invalid test parameters: {self.name}", Fore.RED)) + return False + return True + +class TestSuite: + """Handles loading and running test cases""" + def __init__(self, config_file): + self.config = self.load_config(config_file) + self.exe = self.config["exe"] + self.filename = self.config["filename"] + self.tests = [TestCase(**test) for test in self.config["tests"]] + + @staticmethod + def load_config(filename): + """Loads test cases from JSON""" + with open(filename, "r", encoding="utf-8") as f: + return json.load(f) + +def run_command(cmd, exit_on_error=False): + """Runs a shell command and handles errors""" + try: + result = subprocess.run(cmd, shell=True, capture_output=True, text=True) + return result + except subprocess.CalledProcessError as e: + print(color_text(f"[ERROR] Command failed: {cmd}", Fore.RED)) + print(e.stderr) + if exit_on_error: + exit(1) + return None + +def generate_expected_matrix(n, m, k): + """Generates expected matrix based on k""" + def f(k, i, j): + if k == 1: + return max(n, m) - max(i, j) + 1 + elif k == 2: + return max(i, j) + elif k == 3: + return abs(i - j) + elif k == 4: + return 1.0 / (i + j - 1) if (i + j - 1) != 0 else 0 + return 0 + + matrix = [] + for i in range(n): + row = [f(k, i + 1, j + 1) for j in range(m)] + matrix.append(" ".join(f"{num:10.3e}" for num in row)) + return "\n".join(matrix) + +def wait_for_executable(exe): + """Waits for the executable file to appear after compilation""" + print(color_text(f"[WAIT] Waiting for {exe} to be compiled...", Fore.YELLOW)) + while not os.path.exists(exe): + time.sleep(0.1) # Reduce CPU usage + print(color_text(f"[READY] {exe} compiled successfully.", Fore.GREEN)) + +def format_matrix(matrix): + """Formats a matrix to match `printf("%10.3e")` output""" + formatted = [] + for row in matrix.strip().split("\n"): + formatted.append(" ".join(f"{float(num):10.3e}" for num in row.split())) + return "\n".join(formatted) + +def result_matrix_output(output): + parts = output.split("Result matrix:\n") + if len(parts) > 1: + matrix_lines = parts[1].strip().split("\n") + return format_matrix("\n".join(matrix_lines[:-1])) + return "" + +def initial_matrix_output(output): + parts = output.split("Initial matrix:\n") + if len(parts) > 1: + parts = parts[1].split("Result") + matrix_lines = parts[0].strip().split("\n") + return format_matrix("\n".join(matrix_lines)) + return "" + +def ep2_matrix(matrix, i, j): + rows = matrix.strip().split("\n") + ep2 = [row.strip().split() for row in rows] + try: + for k in range(len(rows)): ep2[k][i-1], ep2[k][j-1] = ep2[k][j-1], ep2[k][i-1] + except IndexError: + print(ep2) + return "\n".join(" ".join(f"{float(num):10.3e}" for num in row) for row in ep2) + +def run_test(test_suite, test): + """Runs the program and checks its result""" + if not test.validate_inputs(): + return + + exe, filename = test_suite.exe, test_suite.filename + + # If matrix is given, write it to the file + if test.k == 0 and test.matrix: + with open(filename, "w", encoding="utf-8") as f: + f.write(format_matrix(test.matrix.strip()) + "\n") + + if test.k != 0: + if test.n is None or test.m is None: + print(color_text(f"[ERROR] Missing 'n' or 'm' for test '{test.name}' with k={test.k}", Fore.RED)) + return + else: + test.matrix = generate_expected_matrix(test.n, test.m, test.k) + + test.matrix = generate_expected_matrix(test.n, test.m, test.k) + + cmd = [exe, str(test.i), str(test.j), str(test.n), str(test.m), str(test.p), str(test.k)] + if test.k == 0: + cmd.append(filename) + + # Run the program + result = run_command(cmd) + + # Extract both initial and result matrices + initial_matrix = initial_matrix_output(result.stdout) + result_matrix = result_matrix_output(result.stdout) + + expected_transposed = ep2_matrix(initial_matrix, test.i, test.j) + + if result_matrix.strip() != expected_transposed.strip(): + print(color_text(f"[FAIL] Test '{test.name}' matrix mismatch.", Fore.RED)) + print(f"Expected:\n{expected_transposed}") + print(f"Got:\n{result_matrix}") + return + + print(color_text(f"[PASS] Test '{test.name}' passed.", Fore.GREEN)) + + if test.k == 0: + # Cleanup test file + try: + os.remove(filename) + except (FileNotFoundError, PermissionError): + print(color_text(f"[WARNING] Could not delete {filename}, Windows may be locking it.", Fore.RED)) + + +def main(): + print(color_text("[CLEAN] Cleaning project...", Fore.BLUE)) + run_command("make clean", exit_on_error=True) + + print(color_text("[BUILD] Compiling project...", Fore.BLUE)) + run_command("make", exit_on_error=True) + + test_suite = TestSuite("test_cases.json") + wait_for_executable(test_suite.exe) + + for test in test_suite.tests: + run_test(test_suite, test) + + print(color_text("[CLEAN] Final cleanup...", Fore.BLUE)) + run_command("make clean") + +if __name__ == "__main__": + main() diff --git a/2025.03.07/8Ex/Makefile b/2025.03.07/8Ex/Makefile new file mode 100644 index 0000000..5d51a05 --- /dev/null +++ b/2025.03.07/8Ex/Makefile @@ -0,0 +1,19 @@ +FLAGS = -fstack-protector-all -W -Wall -Wextra -Wunused -Wcast-align -Werror -pedantic -pedantic-errors -Wfloat-equal -Wpointer-arith -Wformat-security -Wmissing-format-attribute -Wformat=1 -Wwrite-strings -Wcast-align -Wno-long-long -std=gnu99 -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wold-style-definition -Wdeclaration-after-statement -Wbad-function-cast -Wnested-externs -O3 + +a08.exe: main.o array_io.o solve.o init_f.o + gcc main.o solve.o array_io.o init_f.o -o a08.exe -lssp + +main.o: main.c + gcc $(CFLAGS) -c main.c + +solve.o: solve.c + gcc $(FLAGS) -c solve.c + +array_io.o: array_io.c + gcc $(CFLAGS) -c array_io.c + +init_f.o: init_f.c + gcc $(CFLAGS) -c init_f.c + +clean: + del *.o *.exe diff --git a/2025.03.07/8Ex/array_io.c b/2025.03.07/8Ex/array_io.c new file mode 100644 index 0000000..6e56ecf --- /dev/null +++ b/2025.03.07/8Ex/array_io.c @@ -0,0 +1,40 @@ +#include +#include "array_io.h" + +io_status read_matrix(double *a, int n, int m, const char *name) +{ + int i, j; + FILE *fp; + if (!(fp = fopen(name, "r"))) return ERROR_OPEN; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + if (fscanf(fp, "%lf", a + i * m + j) != 1) + {fclose(fp); return ERROR_READ;} + fclose(fp); + return SUCCESS; +} + +void print_matrix(const double *a, int n, int m, int p) +{ + int np = (n > p ? p : n); + int mp = (m > p ? p : m); + int i, j; + + for (i = 0; i < np; i++) + { + for (j = 0; j < mp; j++) + printf(" %10.3e", a[i * m + j]); + printf("\n"); + } +} + +void init_matrix(double *a, int n, int m, int k) +{ + double (*q)(int, int, int, int); + double (*f[])(int, int, int, int) = {f1, f2, f3, f4}; + int i, j; + q = f[k-1]; + for (i = 0; i < n; i++) + for (j = 0; j < m; j++) + a[i * m + j] = q(n, m, i+1, j+1); +} diff --git a/2025.03.07/8Ex/array_io.h b/2025.03.07/8Ex/array_io.h new file mode 100644 index 0000000..e312a84 --- /dev/null +++ b/2025.03.07/8Ex/array_io.h @@ -0,0 +1,11 @@ +#ifndef ARRAY_IO_H +#define ARRAY_IO_H + +#include "io_status.h" +#include "init_f.h" + +io_status read_matrix(double *a, int n, int m, const char *name); +void print_matrix(const double *a, int n, int m, int p); +void init_matrix(double *a, int n, int m, int k); + +#endif diff --git a/2025.03.07/8Ex/init_f.c b/2025.03.07/8Ex/init_f.c new file mode 100644 index 0000000..cf325c3 --- /dev/null +++ b/2025.03.07/8Ex/init_f.c @@ -0,0 +1,30 @@ +#include "init_f.h" +#include + +#define MAX(n, m) (n < m ? m : n) + +double f1(int n, int m, int i, int j) +{ + return MAX(n, m) - MAX(i, j) + 1; +} + +double f2(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return MAX(i, j); +} + +double f3(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return abs(i - j); +} + +double f4(int n, int m, int i, int j) +{ + (void)n; + (void)m; + return 1./(i+j-1); +} diff --git a/2025.03.07/8Ex/init_f.h b/2025.03.07/8Ex/init_f.h new file mode 100644 index 0000000..691aace --- /dev/null +++ b/2025.03.07/8Ex/init_f.h @@ -0,0 +1,9 @@ +#ifndef INIT_F_H +#define INIT_F_H + +double f1(int n, int m, int i, int j); +double f2(int n, int m, int i, int j); +double f3(int n, int m, int i, int j); +double f4(int n, int m, int i, int j); + +#endif diff --git a/2025.03.07/8Ex/io_status.h b/2025.03.07/8Ex/io_status.h new file mode 100644 index 0000000..a51376d --- /dev/null +++ b/2025.03.07/8Ex/io_status.h @@ -0,0 +1,14 @@ +#ifndef IO_STATUS_H +#define IO_STATUS_H + +#define LEN 1234 + +typedef enum _io_status +{ + SUCCESS, + ERROR_OPEN, + ERROR_READ, + ERROR_MEM +} io_status; + +#endif diff --git a/2025.03.07/8Ex/main.c b/2025.03.07/8Ex/main.c new file mode 100644 index 0000000..1c19eb9 --- /dev/null +++ b/2025.03.07/8Ex/main.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include "array_io.h" +#include "io_status.h" +#include "solve.h" + +/* ./a.out i j g n m p k [filename] */ +int main(int argc, char *argv[]) +{ + double g, t, res, *a; + int i, j, n, m, p, k, task = 8; + char *name = 0; + + if (!((argc == 8 || argc == 9) && + sscanf(argv[1], "%d", &i) == 1 && + sscanf(argv[2], "%d", &j) == 1 && + sscanf(argv[3], "%lf", &g) == 1 && + sscanf(argv[4], "%d", &n) == 1 && + sscanf(argv[5], "%d", &m) == 1 && + sscanf(argv[6], "%d", &p) == 1 && + sscanf(argv[7], "%d", &k) == 1 && + k >= 0 && k <= 4 && (!(k == 0 && argc != 9)) && + (i <= n && j <= m) && (i > 0 && j > 0))) + { + printf("Usage: %s i j g n m p k [filename]\n", argv[0]); + return 1; + } + if (argc == 9) name = argv[8]; + + a = (double *)malloc(n * m * sizeof(double)); + if (!a) + { + printf("Not enough memory\n"); + return 2; + } + + if (name) + { /* из файла */ + io_status ret; + ret = read_matrix(a, n, m, name); + do { + switch (ret) + { + case SUCCESS: + continue; + case ERROR_OPEN: + printf("Cannot open %s\n", name); + break; + case ERROR_READ: + printf("Cannot read %s\n", name); + } + free(a); + return 3; + } while (0); + } else init_matrix(a, n, m, k); + + printf("Initial matrix:\n"); + print_matrix(a, n, m, p); + + t = clock(); + t8_solve(a, n, m, i-1, j-1, g); + t = (clock() - t) / CLOCKS_PER_SEC; + + printf("Result matrix:\n"); + print_matrix(a, n, m, p); + printf("%s : Task = %d Elapsed = %.2f\n", argv[0], task, t); + free(a); + return 0; +} diff --git a/2025.03.07/8Ex/solve.c b/2025.03.07/8Ex/solve.c new file mode 100644 index 0000000..f69b840 --- /dev/null +++ b/2025.03.07/8Ex/solve.c @@ -0,0 +1,10 @@ +#include "solve.h" +#include "math.h" + +void t8_solve(double *a, int n, int m, int i, int j, double g) +{ + int k; + (void)n; + for (k = 0; k < m; k++) + a[j * m + k] += a[i * m + k] * g; +} diff --git a/2025.03.07/8Ex/solve.h b/2025.03.07/8Ex/solve.h new file mode 100644 index 0000000..4eef1ed --- /dev/null +++ b/2025.03.07/8Ex/solve.h @@ -0,0 +1,6 @@ +#ifndef SOLVE_H +#define SOLVE_H + +void t8_solve(double *a, int n, int m, int i, int j, double g); + +#endif diff --git a/2025.03.07/8Ex/t.txt b/2025.03.07/8Ex/t.txt new file mode 100644 index 0000000..65c2e7c --- /dev/null +++ b/2025.03.07/8Ex/t.txt @@ -0,0 +1,5 @@ +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 +17 18 19 20 diff --git a/2025.03.07/8Ex/test_cases.json b/2025.03.07/8Ex/test_cases.json new file mode 100644 index 0000000..b2e015c --- /dev/null +++ b/2025.03.07/8Ex/test_cases.json @@ -0,0 +1,123 @@ +{ + "exe": "a08.exe", + "filename": "matrix.txt", + "tests": [ + { + "name": "File Matrix Test", + "i": 1, + "j": 2, + "g": 2, + "k": 0, + "p": 5, + "matrix": "1 2 3 4\n5 6 7 8\n9 10 11 12\n13 14 15 16\n17 18 19 20" + }, + { + "name": "Basic Addition", + "i": 1, + "j": 2, + "g": 2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Negative Gamma", + "i": 1, + "j": 3, + "g": -1, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Large 1000x1000 Matrix", + "i": 500, + "j": 999, + "g": 1.5, + "n": 1000, + "m": 1000, + "k": 1 + }, + { + "name": "Floating Point Values", + "i": 1, + "j": 3, + "g": 0.5, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1.1 2.2 3.3\n4.4 5.5 6.6\n7.7 8.8 9.9" + }, + { + "name": "Negative Values", + "i": 1, + "j": 2, + "g": -2, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "-1 -2 -3\n-4 -5 -6\n-7 -8 -9" + }, + { + "name": "Adding a Row to Itself (Should Double)", + "i": 2, + "j": 2, + "g": 1, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Adding Row with Gamma = 0 (No Change)", + "i": 1, + "j": 3, + "g": 0, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 2 3\n4 5 6\n7 8 9" + }, + { + "name": "Identity Matrix Transformation", + "i": 2, + "j": 3, + "g": 1, + "n": 3, + "m": 3, + "p": 3, + "k": 0, + "matrix": "1 0 0\n0 1 0\n0 0 1" + }, + { + "name": "All Zeroes", + "i": 1, + "j": 2, + "g": 5, + "n": 4, + "m": 4, + "p": 4, + "k": 0, + "matrix": "0 0 0 0\n0 0 0 0\n0 0 0 0\n0 0 0 0" + }, + { + "name": "Different Row Sizes", + "i": 2, + "j": 3, + "g": 3, + "n": 4, + "m": 5, + "p": 5, + "k": 0, + "matrix": "10 20 30 40 50\n60 70 80 90 100\n110 120 130 140 150\n160 170 180 190 200" + } + ] +} diff --git a/2025.03.07/8Ex/test_runner.py b/2025.03.07/8Ex/test_runner.py new file mode 100644 index 0000000..375ff4e --- /dev/null +++ b/2025.03.07/8Ex/test_runner.py @@ -0,0 +1,176 @@ +import json +import subprocess +import os +import time +import platform +import re +import signal +from colorama import Fore, Style, init + +# Enable color support in Windows +init(autoreset=True) + +def color_text(text, color): + """Returns colored text""" + return color + text + Style.RESET_ALL + +def cleanup_and_exit(): + """Handles cleanup on Ctrl+C or forced exit""" + print(color_text("\n[ABORT] Operation interrupted. Cleaning up...", Fore.RED)) + run_command("make clean") + exit(1) + +# Register Ctrl+C handler +signal.signal(signal.SIGINT, lambda sig, frame: cleanup_and_exit()) + +class TestCase: + """Represents a single test case""" + def __init__(self, i, j, g, k, matrix=None, n=None, m=None, p=None, debug=False, name=None): + self.i = i + self.j = j + self.g = g + self.k = k + self.matrix = matrix + self.n = n + self.m = m + self.p = p + self.debug = debug + self.name = name if name else f"Test k={k}, n={n if n else 'auto'}, m={m if m else 'auto'}, p={p if p else 'auto'}" + + # Compute `n` if missing and `k == 0` + if self.k == 0 and self.matrix: + if not self.n: + self.n = len(self.matrix.strip().split("\n")) + if not self.m: + self.m = len(self.matrix.strip().split("\n")[0].split()) + + # Compute `p` + self.p = self.p if self.p else self.n + + def validate_inputs(self): + """Ensures input values are valid""" + if self.k < 0 or (self.k == 0 and not self.matrix): + print(color_text(f"[ERROR] Invalid test parameters: {self.name}", Fore.RED)) + return False + return True + +class TestSuite: + """Handles loading and running test cases""" + def __init__(self, config_file): + self.config = self.load_config(config_file) + self.exe = self.config["exe"] + self.filename = self.config["filename"] + self.tests = [TestCase(**test) for test in self.config["tests"]] + + @staticmethod + def load_config(filename): + """Loads test cases from JSON""" + with open(filename, "r", encoding="utf-8") as f: + return json.load(f) + +def run_command(cmd, exit_on_error=False): + """Runs a shell command and handles errors""" + try: + result = subprocess.run(cmd, shell=True, capture_output=True, text=True) + return result + except subprocess.CalledProcessError as e: + print(color_text(f"[ERROR] Command failed: {cmd}", Fore.RED)) + print(e.stderr) + if exit_on_error: + exit(1) + return None + +def wait_for_executable(exe): + """Waits for the executable file to appear after compilation""" + print(color_text(f"[WAIT] Waiting for {exe} to be compiled...", Fore.YELLOW)) + while not os.path.exists(exe): + time.sleep(0.1) # Reduce CPU usage + print(color_text(f"[READY] {exe} compiled successfully.", Fore.GREEN)) + +def format_matrix(matrix): + """Formats a matrix to match `printf("%10.3e")` output""" + formatted = [] + for row in matrix.strip().split("\n"): + formatted.append(" ".join(f"{float(num):10.3e}" for num in row.split())) + return "\n".join(formatted) + +def result_matrix_output(output): + parts = output.split("Result matrix:\n") + if len(parts) > 1: + matrix_lines = parts[1].strip().split("\n") + return format_matrix("\n".join(matrix_lines[:-1])) + return "" + +def initial_matrix_output(output): + parts = output.split("Initial matrix:\n") + if len(parts) > 1: + parts = parts[1].split("Result") + matrix_lines = parts[0].strip().split("\n") + return format_matrix("\n".join(matrix_lines)) + return "" + +def ep1_matrix(matrix, i, j, g): + rows = matrix.strip().split("\n") + ep1 = [[float(num) for num in row.split()] for row in rows] + for k in range(len(ep1[0])): ep1[j][k] += ep1[i][k] * g + return "\n".join(" ".join(f"{num:10.3e}" for num in row) for row in ep1) + +def run_test(test_suite, test): + """Runs the program and checks its result""" + if not test.validate_inputs(): + return + + exe, filename = test_suite.exe, test_suite.filename + + # If matrix is given, write it to the file + if test.k == 0 and test.matrix: + with open(filename, "w", encoding="utf-8") as f: + f.write(format_matrix(test.matrix.strip()) + "\n") + + cmd = [exe, str(test.i), str(test.j), str(test.g), str(test.n), str(test.m), str(test.p), str(test.k)] + if test.k == 0: + cmd.append(filename) + + # Run the program + result = run_command(cmd) + + # Extract both initial and result matrices + initial_matrix = initial_matrix_output(result.stdout) + result_matrix = result_matrix_output(result.stdout) + + expected_transposed = ep1_matrix(initial_matrix, test.i-1, test.j-1, test.g) + + if result_matrix.strip() != expected_transposed.strip(): + print(color_text(f"[FAIL] Test '{test.name}' matrix mismatch.", Fore.RED)) + print(f"Expected:\n{expected_transposed}") + print(f"Got:\n{result_matrix}") + return + + print(color_text(f"[PASS] Test '{test.name}' passed.", Fore.GREEN)) + + if test.k == 0: + # Cleanup test file + try: + os.remove(filename) + except (FileNotFoundError, PermissionError): + print(color_text(f"[WARNING] Could not delete {filename}, Windows may be locking it.", Fore.RED)) + + +def main(): + print(color_text("[CLEAN] Cleaning project...", Fore.BLUE)) + run_command("make clean", exit_on_error=True) + + print(color_text("[BUILD] Compiling project...", Fore.BLUE)) + run_command("make", exit_on_error=True) + + test_suite = TestSuite("test_cases.json") + wait_for_executable(test_suite.exe) + + for test in test_suite.tests: + run_test(test_suite, test) + + print(color_text("[CLEAN] Final cleanup...", Fore.BLUE)) + run_command("make clean") + +if __name__ == "__main__": + main()