Skip to content

Commit

Permalink
feat: counting functions
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikitosiki committed Feb 11, 2024
1 parent 7d17202 commit 61fccfa
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 25 deletions.
9 changes: 1 addition & 8 deletions src/functions/inverseMatrix.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import { isSquareMatrix } from "./utils";

// Пошук оберненої матриці для довільної квадратної матриці
function inverseMatrix(matrix: number[][]): number[][] | null {
const n = matrix.length;

// Перевірка, чи матриця є квадратною
if (!isSquareMatrix(matrix)) {
return null;
}

// Створення одиничної матриці
const identityMatrix: number[][] = Array.from({ length: n }, (_, i) =>
Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))
);

// Копія вхідної матриці для уникнення змін у вхідних даних
const augmentedMatrix: number[][] = matrix.map((row) => [
...row,
...identityMatrix[matrix.indexOf(row)],
Expand All @@ -24,10 +20,9 @@ function inverseMatrix(matrix: number[][]): number[][] | null {
const pivot = augmentedMatrix[i][i];

if (pivot === 0) {
return null; // Матриця не має оберненої матриці
return null;
}

// Кроки Звичайних Жорданових виключень
for (let j = 0; j < 2 * n; j++) {
augmentedMatrix[i][j] /= pivot;
}
Expand All @@ -42,9 +37,7 @@ function inverseMatrix(matrix: number[][]): number[][] | null {
}
}

// Витягнення оберненої матриці з розширеної матриці
const inverse: number[][] = augmentedMatrix.map((row) => row.slice(n));

return inverse;
}

Expand Down
9 changes: 2 additions & 7 deletions src/functions/matrixRank.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,29 @@ function calculateMatrixRank(matrix: number[][]): number {

const numRows = augmentedMatrix.length;
const numCols = augmentedMatrix[0].length;

let rank = 0;

for (let col = 0; col < numCols && rank < numRows; col++) {
// Знаходження ненульового елемента в стовпці col
let nonZeroRow = rank;
while (nonZeroRow < numRows && augmentedMatrix[nonZeroRow][col] === 0) {
nonZeroRow++;
}

if (nonZeroRow === numRows) {
continue; // Всі рядки під колом col мають нульові значення, переходимо до наступного стовпця
continue;
}

// Обмін рядками, щоб мати ненульовий елемент на позначеній позиції
[augmentedMatrix[rank], augmentedMatrix[nonZeroRow]] = [augmentedMatrix[nonZeroRow], augmentedMatrix[rank]];

// Зрізання стовпця до ненульового елемента, щоб усі інші рядки мали нульові значення
for (let i = rank + 1; i < numRows; i++) {
const factor = augmentedMatrix[i][col] / augmentedMatrix[rank][col];
for (let j = col; j < numCols; j++) {
augmentedMatrix[i][j] -= factor * augmentedMatrix[rank][j];
}
}

rank++;
}

return rank;
}

Expand Down
2 changes: 0 additions & 2 deletions src/functions/solveLinearSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@ import inverseMatrix from "./inverseMatrix";
function solveLinearSystem(matrix: number[][], constants: number[]): number[] | null {
const n = matrix.length;

// Обчислення оберненої матриці
const inverse = inverseMatrix(matrix);

if (!inverse) {
return null;
}

// Обчислення вектора розв'язку
const solution: number[] = [];
for (let i = 0; i < n; i++) {
let sum = 0;
Expand Down
22 changes: 14 additions & 8 deletions src/functions/utils.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
// Проверка квадратной ли матрица
export function isSquareMatrix(matrix: number[][]): boolean {
const rows = matrix.length;
if (rows === 0) {
return false; // Пустая матрица не считается квадратной
return false;
}

for (const row of matrix) {
if (row.length !== rows) {
return false; // Если хотя бы одна строка не имеет той же длины, что и количество строк, то это не квадратная матрица
return false;
}
}

return true;
}

// Виведення матриці
export function roundedRow(row: number[]) {
return row.map((value) => {
const res = Math.round(value * 1000) / 1000;
if (Object.is(res, -0)) return 0;
else return res;
});
}

export function roundedMatrix(matrix: number[][]): number[][] {
return matrix.map((value) => roundedRow(value));
}

export function printMatrix(matrix: number[][]): void {
for (const row of matrix) {
console.log(roundedRow(row).join("\t"));
}
}

export function roundedRow(row: number[]) {
return row.map((value) => Math.round(value * 1000) / 1000);
}

0 comments on commit 61fccfa

Please sign in to comment.