The First task is done

This commit is contained in:
AZEN-SGG 2025-03-02 18:10:27 +03:00
parent 0e3d948c9f
commit 136c9f6b00
16 changed files with 469 additions and 0 deletions

19
2025.03.07/1Ex/Makefile Normal file
View file

@ -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
a01.exe: main.o array_io.o solve.o init_f.o
gcc main.o solve.o array_io.o init_f.o -o a01.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

39
2025.03.07/1Ex/array_io.c Normal file
View file

@ -0,0 +1,39 @@
#include <stdio.h>
#include "array_io.h"
io_status read_sq_matrix(double *a, int n, 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 < n; j++)
if (fscanf(fp, "%lf", a + i * n + j) != 1)
{fclose(fp); return ERROR_READ;}
fclose(fp);
return SUCCESS;
}
void print_sq_matrix(const double *a, int n, int p)
{
int np = (n > p ? p : n);
int i, j;
for (i = 0; i < np; i++)
{
for (j = 0; j < np; j++)
printf(" %10.3e", a[i * n + j]);
printf("\n");
}
}
void init_sq_matrix(double *a, int n, 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 < n; j++)
a[i * n + j] = q(n, n, i+1, j+1);
}

11
2025.03.07/1Ex/array_io.h Normal file
View file

@ -0,0 +1,11 @@
#ifndef ARRAY_IO_H
#define ARRAY_IO_H
#include "io_status.h"
#include "init_f.h"
io_status read_sq_matrix(double *a, int n, const char *name);
void print_sq_matrix(const double *a, int n, int p);
void init_sq_matrix(double *a, int n, int k);
#endif

30
2025.03.07/1Ex/init_f.c Normal file
View file

@ -0,0 +1,30 @@
#include "init_f.h"
#include <math.h>
#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);
}

9
2025.03.07/1Ex/init_f.h Normal file
View file

@ -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

View file

@ -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

64
2025.03.07/1Ex/main.c Normal file
View file

@ -0,0 +1,64 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n p k [filename] */
int main(int argc, char *argv[])
{
double t, *a;
int n, p, k, res, task = 1;
char *name = 0;
if (!((argc == 4 || argc == 5) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &p) == 1 &&
sscanf(argv[3], "%d", &k) == 1 &&
k >= 0 && k <= 4 && (!(k == 0 && argc != 5))))
{
printf("Usage: %s n p k [filename]\n", argv[0]);
return 0;
}
if (argc == 5) name = argv[4];
a = (double *)malloc(n * n * sizeof(double));
if (!a)
{
printf("Not enough memory\n");
return 2;
}
if (name)
{ /* из файла */
io_status ret;
ret = read_sq_matrix(a, n, 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_sq_matrix(a, n, k);
printf("initial matrix:\n");
print_sq_matrix(a, n, p);
t = clock();
res = t1_solve(a, n);
t = (clock() - t) / CLOCKS_PER_SEC;
printf("Result = %d\n", res);
printf("%s : Task = %d Elapsed = %.2f\n", argv[0], task, t);
free(a);
return 0;
}

View file

@ -0,0 +1,4 @@
1.000e+00 2.000e+00 3.000e+00 4.000e+00
2.000e+00 3.000e+00 4.000e+00 5.000e+00
3.000e+00 4.000e+00 5.000e+00 6.000e+00
4.000e+00 5.000e+00 6.000e+00 7.000e+00

14
2025.03.07/1Ex/solve.c Normal file
View file

@ -0,0 +1,14 @@
#include "solve.h"
#include "math.h"
#define eps 1e-6
int t1_solve(double *a, int n)
{
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (i != j)
if (fabs(a[i * n + j] - a[j * n + i]) > eps) return 0;
return n;
}

6
2025.03.07/1Ex/solve.h Normal file
View file

@ -0,0 +1,6 @@
#ifndef SOLVE_H
#define SOLVE_H
int t1_solve(double *a, int n);
#endif

4
2025.03.07/1Ex/t.txt Normal file
View file

@ -0,0 +1,4 @@
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4

View file

@ -0,0 +1,46 @@
{
"exe": "a01.exe",
"filename": "matrix.txt",
"tests": [
{
"name": "File Matrix Test",
"k": 0,
"matrix": "1 2 3 4\n1 2 3 4\n1 2 3 4\n1 2 3 4",
"expected_res": 0
},
{
"name": "File Symmetric Matrix Test",
"k": 0,
"matrix": "1 2 3 4\n2 3 4 5\n3 4 5 6\n4 5 6 7",
"expected_res": 4
},
{
"name": "Generated Matrix (k=1)",
"k": 1,
"n": 3,
"p": 3,
"expected_res": 3
},
{
"name": "Generated Matrix (k=2)",
"k": 2,
"n": 3,
"p": 3,
"expected_res": 3
},
{
"name": "Generated Matrix (k=3)",
"k": 3,
"n": 3,
"p": 3,
"expected_res": 3
},
{
"name": "Generated Matrix (k=4)",
"k": 4,
"n": 3,
"p": 3,
"expected_res": 3
}
]
}

View file

@ -0,0 +1,182 @@
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, k, matrix=None, n=None, p=None, expected_res=0, debug=False, name=None):
self.k = k
self.matrix = matrix
self.n = n
self.p = p
self.expected_res = expected_res
self.debug = debug
self.name = name if name else f"Test k={k}, n={n if n else 'auto'}, p={p if p else 'auto'}"
# Compute `n` if missing and `k == 0`
if self.k == 0 and not self.n and self.matrix:
self.n = len(self.matrix.strip().split("\n"))
# 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 parse_matrix_output(output):
"""Extracts and formats matrix from program output"""
parts = output.split("initial matrix:\n")[1].split("Result")
if len(parts) > 1:
matrix = "\n".join(parts[0].strip().split("\n")) # Remove last line with "Result = ..."
return format_matrix(matrix)
return ""
def check_result(output, expected_res):
"""Checks if Result matches expected value"""
match = re.search(r"Result\s*=\s*(-?\d+)", output)
if match:
result_value = int(match.group(1))
if result_value != expected_res:
print(color_text(f"[FAIL] Test failed: Result = {result_value} (expected {expected_res})", Fore.RED))
return False
return True
def generate_expected_matrix(n, p, k):
"""Generates expected matrix based on k"""
def f(k, i, j):
if k == 1:
return max(n, n) - 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(min(n, p)):
row = [f(k, i + 1, j + 1) for j in range(min(n, p))]
matrix.append(" ".join(f"{num:10.3e}" for num in row))
return "\n".join(matrix)
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.n), str(test.p), str(test.k)]
if test.k == 0:
cmd.append(filename)
# Run the program
result = run_command(cmd)
# Extract and format output matrix
matrix_output = parse_matrix_output(result.stdout) if result else None
# Generate expected matrix
expected_matrix = format_matrix(test.matrix) if test.k == 0 else generate_expected_matrix(test.n, test.p, test.k)
if matrix_output.strip() != expected_matrix.strip():
print(color_text(f"[FAIL] Test '{test.name}' matrix mismatch.", Fore.RED))
print(f"Expected:\n{expected_matrix}")
print(f"Got:\n{matrix_output}")
return
# Check Result
if not check_result(result.stdout, test.expected_res):
return
print(color_text(f"[PASS] Test '{test.name}' passed.", Fore.GREEN))
def main():
print(color_text("[CLEAN] Cleaning project...", Fore.CYAN))
run_command("make clean", exit_on_error=True)
print(color_text("[BUILD] Compiling project...", Fore.CYAN))
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.CYAN))
run_command("make clean")
if __name__ == "__main__":
main()

View file

@ -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.o solve.o sort.o
gcc main.o solve.o array.o sort.o -o a08.exe -lssp
main.o: main.c
gcc $(CFLAGS) -c main.c
solve.o: solve.c
gcc $(FLAGS) -c solve.c
array.o: array.c
gcc $(CFLAGS) -c array.c
sort.o: sort.c
gcc $(CFLAGS) -c sort.c
clean:
del *.o *.exe

View file

@ -0,0 +1,8 @@
#ifndef ARRAY_IO_H
#define ARRAY_IO_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);
#endif

BIN
2025.03.07/Tasks04.pdf Normal file

Binary file not shown.