Tasks from First to Fourth are done!

This commit is contained in:
AZEN-SGG 2025-03-09 19:11:16 +03:00
parent 50cc0f9b65
commit 48d6198ca3
64 changed files with 2217 additions and 13 deletions

3
.gitignore vendored
View file

@ -13,3 +13,6 @@
cmake-build-debug/
.idea/
CMakeLists.txt
# FreeFileSync files
*.ffs_db

View file

@ -3,13 +3,11 @@
void matrix_multiply(const double *A, const double *B, double *c, int n, int m, int l)
{
int i, j, k, index;
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < l; j++)
{
index = i * l + j;
c[index] = 0;
for (k = 0; k < m; k++)
c[index] += A[i * m + k] * B[k * l + j];
{
for (j = 0; j < l; j++)
c[i * l + j] += A[i * m + k] * B[k * l + j];
}
}

View file

@ -101,13 +101,11 @@ void t9_solve(const double *A, const double *b, double *c, int n, int m)
void matrix_multiply(const double *A, const double *B, double *c, int n, int m, int l)
{
int i, j, k, index;
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < l; j++)
{
index = i * l + j;
c[index] = 0;
for (k = 0; k < m; k++)
c[index] += A[i * m + k] * B[k * l + j];
{
for (j = 0; j < l; j++)
c[i * l + j] += A[i * m + k] * B[k * l + j];
}
}

19
2025.03.14/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

40
2025.03.14/1Ex/array_io.c Normal file
View file

@ -0,0 +1,40 @@
#include <stdio.h>
#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);
}

11
2025.03.14/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_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

30
2025.03.14/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.14/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

65
2025.03.14/1Ex/main.c Normal file
View file

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n m p k [filename] */
int main(int argc, char *argv[])
{
double t, res, *a;
int n, m, p, k, task = 1;
char *name = 0;
if (!((argc == 5 || argc == 6) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &m) == 1 &&
sscanf(argv[3], "%d", &p) == 1 &&
sscanf(argv[4], "%d", &k) == 1 &&
k >= 0 && k <= 4 && (!(k == 0 && argc != 6))))
{
printf("Usage: %s n m p k [filename]\n", argv[0]);
return 1;
}
if (argc == 6) name = argv[5];
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();
res = t1_solve(a, n, m);
t = (clock() - t) / CLOCKS_PER_SEC;
printf ("%s : Task = %d Result = %e Elapsed = %.2f\n", argv[0], task, res, t);
free(a);
return 0;
}

28
2025.03.14/1Ex/solve.c Normal file
View file

@ -0,0 +1,28 @@
#include "solve.h"
#include <math.h>
#define eps 1e-9
int compare(const double a, const double b)
{
if (a - b > eps) return 1;
else if (b - a > eps) return -1;
return 0;
}
double t1_solve(double *a, int n, int m)
{
int i, j;
double cur = 0, maximum = 0;
if (n > 0)
for (j = 0; j < m; j++) maximum += fabs(a[j]);
for (i = 1; i < n; i++)
{
cur = 0;
for (j = 0; j < m; j++)
cur = fabs(a[i * m + j]);
if (compare(cur, maximum) == 1) maximum = cur;
}
return maximum;
}

7
2025.03.14/1Ex/solve.h Normal file
View file

@ -0,0 +1,7 @@
#ifndef SOLVE_H
#define SOLVE_H
int compare(const double a, const double b);
double t1_solve(double *a, int n, int m);
#endif

5
2025.03.14/1Ex/t.txt Normal file
View file

@ -0,0 +1,5 @@
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

View file

@ -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"
}
]
}

View file

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

19
2025.03.14/2Ex/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
a02.exe: main.o array_io.o solve.o init_f.o
gcc main.o solve.o array_io.o init_f.o -o a02.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

40
2025.03.14/2Ex/array_io.c Normal file
View file

@ -0,0 +1,40 @@
#include <stdio.h>
#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);
}

11
2025.03.14/2Ex/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_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

30
2025.03.14/2Ex/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.14/2Ex/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

65
2025.03.14/2Ex/main.c Normal file
View file

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n m p k [filename] */
int main(int argc, char *argv[])
{
double t, res, *a;
int n, m, p, k, task = 2;
char *name = 0;
if (!((argc == 5 || argc == 6) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &m) == 1 &&
sscanf(argv[3], "%d", &p) == 1 &&
sscanf(argv[4], "%d", &k) == 1 &&
k >= 0 && k <= 4 && (!(k == 0 && argc != 6))))
{
printf("Usage: %s n m p k [filename]\n", argv[0]);
return 1;
}
if (argc == 6) name = argv[5];
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();
res = t2_solve(a, n, m);
t = (clock() - t) / CLOCKS_PER_SEC;
printf ("%s : Task = %d Result = %e Elapsed = %.2f\n", argv[0], task, res, t);
free(a);
return 0;
}

28
2025.03.14/2Ex/solve.c Normal file
View file

@ -0,0 +1,28 @@
#include "solve.h"
#include <math.h>
#define eps 1e-9
int compare(const double a, const double b)
{
if (a - b > eps) return 1;
else if (b - a > eps) return -1;
return 0;
}
double t2_solve(double *a, int n, int m)
{
int i, j;
double cur = 0, maximum = 0;
if (m > 0)
for (i = 0; i < n; i++) maximum += fabs(a[i * m]);
for (j = 1; j < m; j++)
{
cur = 0;
for (i = 0; i < n; i++)
cur += fabs(a[i * m + j]);
if (compare(cur, maximum) == 1) maximum = cur;
}
return maximum;
}

7
2025.03.14/2Ex/solve.h Normal file
View file

@ -0,0 +1,7 @@
#ifndef SOLVE_H
#define SOLVE_H
int compare(const double a, const double b);
double t2_solve(double *a, int n, int m);
#endif

5
2025.03.14/2Ex/t.txt Normal file
View file

@ -0,0 +1,5 @@
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

View file

@ -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"
}
]
}

View file

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

19
2025.03.14/3Ex/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
a03.exe: main.o array_io.o solve.o init_f.o
gcc main.o solve.o array_io.o init_f.o -o a03.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

2
2025.03.14/3Ex/a.txt Normal file
View file

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

40
2025.03.14/3Ex/array_io.c Normal file
View file

@ -0,0 +1,40 @@
#include <stdio.h>
#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);
}

11
2025.03.14/3Ex/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_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

3
2025.03.14/3Ex/b.txt Normal file
View file

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

30
2025.03.14/3Ex/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.14/3Ex/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

161
2025.03.14/3Ex/main.c Normal file
View file

@ -0,0 +1,161 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n m p k_a [filename_a] k_b [filename_b] k_x [filename_x] */
int main(int argc, char *argv[])
{
double t, res, *a, *b, *x;
int n, m, p, k_a, k_b, k_x, task = 3;
char *name_a = 0, *name_b = 0, *name_x = 0;
if (!((argc >= 7 && argc <= 10) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &m) == 1 &&
sscanf(argv[3], "%d", &p) == 1 &&
sscanf(argv[4], "%d", &k_a) == 1 &&
(k_a >= 0 && k_a <= 4) &&
(!(k_a == 0 && argc == 7)) &&
((k_a == 0 && sscanf(argv[6], "%d", &k_b) == 1) ||
(k_a != 0 && sscanf(argv[5], "%d", &k_b) == 1)) &&
(k_b >= 0 && k_b <= 4) &&
(!(k_b == 0 && ((argc <= 7) || (k_a == 0 && argc <= 8)))) &&
((k_a == 0 && k_b == 0 && sscanf(argv[8], "%d", &k_x) == 1) ||
(k_a != 0 && k_b != 0 && sscanf(argv[6], "%d", &k_x) == 1) ||
(sscanf(argv[7], "%d", &k_x) == 1)) &&
(k_x >= 0 && k_x <= 4) &&
(!(k_x == 0 && ((k_a == 0 && k_b == 0 && argc != 10) ||
(k_a != 0 && k_b != 0 && argc != 8) ||
(k_a != k_b && argc != 9))))))
{
printf("Usage: %s n m p k_a [filename_a] k_b [filename_b] k_x [filename_x]\n", argv[0]);
return 1;
}
if (argc != 7)
{
int i_b = 6;
if (k_a == 0) { name_a = argv[5]; i_b++; }
if (k_b == 0) { name_b = argv[i_b]; i_b+=2; }
else i_b++;
if (k_x == 0) name_x = argv[i_b];
}
a = (double *)malloc(n * m * sizeof(double));
if (!a)
{
printf("Not enough memory\n");
return 2;
}
b = (double *)malloc(n * sizeof(double));
if (!b)
{
free(a);
printf("Not enough memory\n");
return 2;
}
x = (double *)malloc(m * sizeof(double));
if (!x)
{
free(a);
free(b);
printf("Not enough memory\n");
return 2;
}
if (name_a)
{ /* Читаем матрицу A из файла */
io_status ret;
ret = read_matrix(a, n, m, name_a);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_a);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_a);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(a, n, m, k_a);
if (name_b)
{ /* Читаем матрицу B из файла */
io_status ret;
ret = read_matrix(b, n, 1, name_b);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_b);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_b);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(b, n, 1, k_b);
if (name_x)
{ /* Читаем матрицу X из файла */
io_status ret;
ret = read_matrix(x, m, 1, name_x);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_x);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_x);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(x, m, 1, k_x);
printf("Initial matrix A:\n");
print_matrix(a, n, m, p);
printf("Initial vector b:\n");
print_matrix(b, n, 1, p);
printf("Initial vector x:\n");
print_matrix(x, m, 1, p);
t = clock();
res = t3_solve(a, x, b, m, n);
t = (clock() - t) / CLOCKS_PER_SEC;
printf ("%s : Task = %d Result = %e Elapsed = %.2f\n", argv[0], task, res, t);
free(a);
free(b);
free(x);
return 0;
}

18
2025.03.14/3Ex/solve.c Normal file
View file

@ -0,0 +1,18 @@
#include "solve.h"
#include "math.h"
double t3_solve(const double *A, const double *X, double *B, int m, int n)
{
double r = 0;
int i, j;
for (i = 0; i < n; i++) B[i] = -B[i];
for (i = 0; i < n; i++)
{
for (j = 0; j < m; j++)
B[i] += A[i * m + j] * X[j];
r += fabs(B[i]);
}
return r;
}

6
2025.03.14/3Ex/solve.h Normal file
View file

@ -0,0 +1,6 @@
#ifndef SOLVE_H
#define SOLVE_H
double t3_solve(const double *A, const double *X, double *B, int m, int n);
#endif

3
2025.03.14/3Ex/x.txt Normal file
View file

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

19
2025.03.14/4Ex/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
a04.exe: main.o array_io.o solve.o init_f.o
gcc main.o solve.o array_io.o init_f.o -o a04.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

2
2025.03.14/4Ex/a.txt Normal file
View file

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

40
2025.03.14/4Ex/array_io.c Normal file
View file

@ -0,0 +1,40 @@
#include <stdio.h>
#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);
}

11
2025.03.14/4Ex/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_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

3
2025.03.14/4Ex/b.txt Normal file
View file

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

30
2025.03.14/4Ex/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.14/4Ex/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

161
2025.03.14/4Ex/main.c Normal file
View file

@ -0,0 +1,161 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n m p k_a [filename_a] k_b [filename_b] k_x [filename_x] */
int main(int argc, char *argv[])
{
double t, res, *a, *b, *x;
int n, m, p, k_a, k_b, k_x, task = 4;
char *name_a = 0, *name_b = 0, *name_x = 0;
if (!((argc >= 7 && argc <= 10) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &m) == 1 &&
sscanf(argv[3], "%d", &p) == 1 &&
sscanf(argv[4], "%d", &k_a) == 1 &&
(k_a >= 0 && k_a <= 4) &&
(!(k_a == 0 && argc == 7)) &&
((k_a == 0 && sscanf(argv[6], "%d", &k_b) == 1) ||
(k_a != 0 && sscanf(argv[5], "%d", &k_b) == 1)) &&
(k_b >= 0 && k_b <= 4) &&
(!(k_b == 0 && ((argc <= 7) || (k_a == 0 && argc <= 8)))) &&
((k_a == 0 && k_b == 0 && sscanf(argv[8], "%d", &k_x) == 1) ||
(k_a != 0 && k_b != 0 && sscanf(argv[6], "%d", &k_x) == 1) ||
(sscanf(argv[7], "%d", &k_x) == 1)) &&
(k_x >= 0 && k_x <= 4) &&
(!(k_x == 0 && ((k_a == 0 && k_b == 0 && argc != 10) ||
(k_a != 0 && k_b != 0 && argc != 8) ||
(k_a != k_b && argc != 9))))))
{
printf("Usage: %s n m p k_a [filename_a] k_b [filename_b] k_x [filename_x]\n", argv[0]);
return 1;
}
if (argc != 7)
{
int i_b = 6;
if (k_a == 0) { name_a = argv[5]; i_b++; }
if (k_b == 0) { name_b = argv[i_b]; i_b+=2; }
else i_b++;
if (k_x == 0) name_x = argv[i_b];
}
a = (double *)malloc(n * m * sizeof(double));
if (!a)
{
printf("Not enough memory\n");
return 2;
}
b = (double *)malloc(n * sizeof(double));
if (!b)
{
free(a);
printf("Not enough memory\n");
return 2;
}
x = (double *)malloc(m * sizeof(double));
if (!x)
{
free(a);
free(b);
printf("Not enough memory\n");
return 2;
}
if (name_a)
{ /* Читаем матрицу A из файла */
io_status ret;
ret = read_matrix(a, n, m, name_a);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_a);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_a);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(a, n, m, k_a);
if (name_b)
{ /* Читаем матрицу B из файла */
io_status ret;
ret = read_matrix(b, n, 1, name_b);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_b);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_b);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(b, n, 1, k_b);
if (name_x)
{ /* Читаем матрицу X из файла */
io_status ret;
ret = read_matrix(x, m, 1, name_x);
do {
switch (ret)
{
case SUCCESS:
continue;
case ERROR_OPEN:
printf("Cannot open %s\n", name_x);
break;
case ERROR_READ:
printf("Cannot read %s\n", name_x);
break;
}
free(a);
free(b);
free(x);
return 3;
} while (0);
}
else init_matrix(x, m, 1, k_x);
printf("Initial matrix A:\n");
print_matrix(a, n, m, p);
printf("Initial vector b:\n");
print_matrix(b, n, 1, p);
printf("Initial vector x:\n");
print_matrix(x, m, 1, p);
t = clock();
res = t4_solve(a, x, b, m, n);
t = (clock() - t) / CLOCKS_PER_SEC;
printf ("%s : Task = %d Result = %e Elapsed = %.2f\n", argv[0], task, res, t);
free(a);
free(b);
free(x);
return 0;
}

28
2025.03.14/4Ex/solve.c Normal file
View file

@ -0,0 +1,28 @@
#include "solve.h"
#include "math.h"
#define eps 1e-9
int compare(const double a, const double b)
{
if (a - b > eps) return 1;
else if (b - a > eps) return -1;
return 0;
}
double t4_solve(const double *A, const double *X, double *B, int m, int n)
{
double maximum = -1, cur;
int i, j;
for (i = 0; i < n; i++)
{
cur = -B[i];
for (j = 0; j < m; j++)
cur += A[i * m + j] * X[j];
cur = fabs(cur);
if (compare(cur, maximum) == 1) maximum = cur;
}
return maximum;
}

7
2025.03.14/4Ex/solve.h Normal file
View file

@ -0,0 +1,7 @@
#ifndef SOLVE_H
#define SOLVE_H
int compare(const double a, const double b);
double t4_solve(const double *A, const double *X, double *B, int m, int n);
#endif

3
2025.03.14/4Ex/x.txt Normal file
View file

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

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

View file

@ -0,0 +1,40 @@
#include <stdio.h>
#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);
}

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

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);
}

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

65
2025.03.14/Example/main.c Normal file
View file

@ -0,0 +1,65 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "array_io.h"
#include "io_status.h"
#include "solve.h"
/* ./a.out n m p k [filename] */
int main(int argc, char *argv[])
{
double t, res, *a;
int n, m, p, k, task = 1;
char *name = 0;
if (!((argc == 5 || argc == 6) &&
sscanf(argv[1], "%d", &n) == 1 &&
sscanf(argv[2], "%d", &m) == 1 &&
sscanf(argv[3], "%d", &p) == 1 &&
sscanf(argv[4], "%d", &k) == 1 &&
k >= 0 && k <= 4 && (!(k == 0 && argc != 6))))
{
printf("Usage: %s n m p k [filename]\n", argv[0]);
return 1;
}
if (argc == 6) name = argv[5];
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();
res = t1_solve(a, n, m);
t = (clock() - t) / CLOCKS_PER_SEC;
printf ("%s : Task = %d Result = %e Elapsed = %.2f\n", argv[0], task, res, t);
free(a);
return 0;
}

View file

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

View file

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

5
2025.03.14/Example/t.txt Normal file
View file

@ -0,0 +1,5 @@
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

View file

@ -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"
}
]
}

View file

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

BIN
2025.03.14/Tasks05.pdf Normal file

Binary file not shown.