Skip to content

Commit

Permalink
✨ add 3x3 resolve system linear
Browse files Browse the repository at this point in the history
  • Loading branch information
Brendon3578 committed Apr 30, 2024
1 parent b622c9e commit 5e371b0
Show file tree
Hide file tree
Showing 4 changed files with 230 additions and 124 deletions.
15 changes: 5 additions & 10 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</head>
<body class="min-h-screen min-w-full flex justify-center mt-10">
<div
class="max-w-2xl p-5 border border-gray-400 rounded shadow-lg flex flex-col gap-3 w-full h-min"
class="max-w-3xl p-5 border border-gray-400 rounded shadow-lg flex flex-col gap-3 w-full h-min"
>
<h1 class="text-center text-lg font-bold">Calcular Sistemas Lineares</h1>
<div class="flex gap-4 flex-col sm:flex-row">
Expand Down Expand Up @@ -70,10 +70,7 @@ <h3>Sistema linear</h3>
<div id="linear-system-illustration" class="p-1"></div>
</div>
<div>
<h3>
Equações na
<span class="text-blue-600"> representação matricial</span>
</h3>
<h3>Sistema linear na representação matricial</h3>
<div id="matrix-illustration" class="p-1"></div>
</div>
</section>
Expand All @@ -92,21 +89,19 @@ <h2 class="text-gray-900 font-bold text-lg">Solução do sistema</h2>
<div class="mb-2">Mensagem: <span id="status-message"> </span></div>
<div class="text-sm">
Classificação do sistema linear:
<span id="system-classification">
SPD Sistema possível determinado
</span>
<span id="system-classification"> ? </span>
</div>
</div>
<div class="flex flex-col sm:flex-row justify-between w-full p-1 gap-2">
<div class="basis-1/4">
<h4>Resultado:</h4>
<h4 class="mb-1">Resultado:</h4>
<ul id="result-list" class="list-disc pl-6">
<li>X = <b class="font-bold">?</b></li>
<li>Y = <b class="font-bold">?</b></li>
</ul>
</div>
<div class="basis-3/4">
<h4>Resultado das Determinantes:</h4>
<h4 class="mb-1">Resultado das Determinantes:</h4>

<ul id="determinant-list" class="flex flex-col md:flex-row gap-4">
<!-- <li class="flex flex-col gap-2 items-center">
Expand Down
234 changes: 162 additions & 72 deletions src/scripts/script.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { MathJaxHTMLWriter } from "./classes/MathJaxHTMLWriter.js";
import { log, roundToThreeDecimalPlaces, writeMatrix } from "./utils.js";
import {
areAllDeterminantsZero,
hasDeterminantsNotEqualsZero,
isDeterminantEqualsZero,
isDeterminantNotEqualsZero,
log,
roundToThreeDecimalPlaces,
writeMatrix,
} from "./utils.js";

/**
* @type { HTMLInputElement }
Expand Down Expand Up @@ -90,42 +98,65 @@ function solveSystem() {
const coeffs_eq1 = extractCoefficients(eq1);
const coeffs_eq2 = extractCoefficients(eq2);

let equationResultOutput = {
classification: { type: "", message: "" },
message: "",
resolutions: [],
determinants: [],
};

if (!is3x3LinearSystem) {
const { resolutions, determinants, classification, message } =
solve2x2System(coeffs_eq1, coeffs_eq2);
resolutions.forEach((solution) => {
resultListEl.innerHTML += `<li>${solution.unknown.toUpperCase()} = <b class="font-bold">${roundToThreeDecimalPlaces(
solution.value
)}</b></li>`;
});

determinants.forEach((determinant) => {
determinantListEl.innerHTML += `
<li class="flex flex-col gap-2 items-center rounded-md shadow-lg p-2 pb-4 border border-gray-400 w-full bg-gradient-to-t from-gray-200 to-white">
<span class="text-sm">Det. de ${determinant.unknown.toUpperCase()} = ${roundToThreeDecimalPlaces(
determinant.result
)}</span>
<div>${determinant.matrixHTML}</div>
</li>`;
});

let classificationTextColors = {
SI: "text-indigo-700",
SPD: "text-teal-700",
SPI: "text-blue-700",
};

let classificationTextColor =
classificationTextColors[classification.type];

systemsClassificationTextEl.innerHTML = `<span class=' ${classificationTextColor} font-bold'> ${classification.message} </span>`;
mathJaxHTMLWriter.updateMathJax();

equationResultOutput.resolutions = resolutions;
equationResultOutput.determinants = determinants;
equationResultOutput.classification = classification;
equationResultOutput.message = message;
} else {
// let eq3 = thirdEquationEl.value;
// const coeffs_eq3 = extractCoefficients(eq3);
// solutions = solve3x3System(coeffs_eq1, coeffs_eq2, coeffs_eq3);
let eq3 = thirdEquationEl.value;
const coeffs_eq3 = extractCoefficients(eq3);
const { resolutions, determinants, classification, message } =
solve3x3System(coeffs_eq1, coeffs_eq2, coeffs_eq3);

equationResultOutput.resolutions = resolutions;
equationResultOutput.determinants = determinants;
equationResultOutput.classification = classification;
equationResultOutput.message = message;
}

equationResultOutput.resolutions.forEach((solution) => {
const result = roundToThreeDecimalPlaces(solution.value);
const unknown = solution.unknown.toUpperCase();
resultListEl.innerHTML += `<li title="Resultado de ${unknown} é igual a ${result}">
${unknown} = <b class="font-bold">${result}</b></li>`;
});

equationResultOutput.determinants.forEach((determinant) => {
const result = roundToThreeDecimalPlaces(determinant.result);
const unknown = determinant.unknown.toUpperCase();
determinantListEl.innerHTML += `
<li
class="flex flex-col gap-2 items-center justify-between rounded-md shadow-lg p-2 pb-4 border border-gray-400 w-full bg-gradient-to-t from-gray-200 to-white"
title="Resultado da determinante de ${unknown} é igual a ${result}"
>
<span class="text-sm font-semibold">Det. de ${unknown} = ${result}</span>
<div>${determinant.matrixHTML}</div>
</li>`;
});

let classificationTextColors = {
SI: "text-indigo-700",
SPD: "text-teal-700",
SPI: "text-blue-700",
};

let classificationTextColor =
classificationTextColors[equationResultOutput.classification.type];

systemsClassificationTextEl.innerHTML = `<span class=' ${classificationTextColor} font-bold'> ${equationResultOutput.classification.message} </span>`;
mathJaxHTMLWriter.updateMathJax();

showStatusMessage("success");
} catch (e) {
console.error(e);
Expand All @@ -151,10 +182,7 @@ function solve2x2System(coeffs_eq1, coeffs_eq2) {
];
const detMain = calculateDeterminant2x2(determinantMainMatrix);

const coefficientMatrix = [
[a, b],
[c, d],
];
const coefficientMatrix = determinantMainMatrix;
const constantMatrix = [x, y];

mathJaxHTMLWriter.drawn2x2MatrixRepresentation(
Expand Down Expand Up @@ -201,13 +229,12 @@ function solve2x2System(coeffs_eq1, coeffs_eq2) {
};
let messageOutput = "Cálculo realizado com sucesso";

if (detMain === 0) {
// return { message: "Sistema não possui solução única" }
if (detX == 0 && detY == 0) {
if (isDeterminantEqualsZero(detMain)) {
if (areAllDeterminantsZero([detX, detY])) {
classificationOutput.type = "SPI";
classificationOutput.message =
"Sistema Possível Indeterminado (SPI) - O sistema tem infinitas soluções";
} else if (detX != 0 || detY != 0) {
} else if (hasDeterminantsNotEqualsZero([detX, detY])) {
classificationOutput.type = "SI";
classificationOutput.message =
"Sistema Impossível (SI) - O sistema não tem solução";
Expand Down Expand Up @@ -243,58 +270,121 @@ function solve2x2System(coeffs_eq1, coeffs_eq2) {
}

function solve3x3System(coeffs_eq1, coeffs_eq2, coeffs_eq3) {
const detMain = calculateDeterminant3x3([
coeffs_eq1.slice(0, 3),
coeffs_eq2.slice(0, 3),
coeffs_eq3.slice(0, 3),
]);

const coefficientMatrix = [
coeffs_eq1.slice(0, 3),
coeffs_eq2.slice(0, 3),
coeffs_eq3.slice(0, 3),
console.log(coeffs_eq1);
console.log(coeffs_eq2);
console.log(coeffs_eq3);
const [a, b, c] = coeffs_eq1.slice(0, 3);
const [d, e, f] = coeffs_eq2.slice(0, 3);
const [g, h, i] = coeffs_eq3.slice(0, 3);

const x = coeffs_eq1[3];
const y = coeffs_eq2[3];
const z = coeffs_eq3[3];

const determinantMainMatrix = [
[a, b, c],
[d, e, f],
[g, h, i],
];
console.log(coefficientMatrix);
const constantMatrix = [coeffs_eq1[3], coeffs_eq2[3], coeffs_eq3[3]];

log("determinant", "Será calculada a determinante da matriz A:");
const detMain = calculateDeterminant3x3(determinantMainMatrix);

const coefficientMatrix = determinantMainMatrix;
const constantMatrix = [x, y, z];

mathJaxHTMLWriter.drawn3x3MatrixRepresentation(
coefficientMatrix,
constantMatrix
);
mathJaxHTMLWriter.drawn3x3LinearSystem(coefficientMatrix, constantMatrix);

if (detMain === 0) {
return "<p>Sistema não possui solução única.</p>";
}

const determinantXMatrix = [
[coeffs_eq1[3], coeffs_eq1[1], coeffs_eq1[2]],
[coeffs_eq2[3], coeffs_eq2[1], coeffs_eq2[2]],
[coeffs_eq3[3], coeffs_eq3[1], coeffs_eq3[2]],
[x, b, c],
[y, e, f],
[z, h, i],
];
const determinantYMatrix = [
[coeffs_eq1[0], coeffs_eq1[3], coeffs_eq1[2]],
[coeffs_eq2[0], coeffs_eq2[3], coeffs_eq2[2]],
[coeffs_eq3[0], coeffs_eq3[3], coeffs_eq3[2]],
[a, x, c],
[d, y, f],
[g, z, i],
];
const determinantZMatrix = [
[coeffs_eq1[0], coeffs_eq1[1], coeffs_eq1[3]],
[coeffs_eq2[0], coeffs_eq2[1], coeffs_eq2[3]],
[coeffs_eq3[0], coeffs_eq3[1], coeffs_eq3[3]],
[a, b, x],
[d, e, y],
[g, h, z],
];
log("determinant", "Será calculada a determinante da matriz X:");
const detX = calculateDeterminant3x3(determinantXMatrix);
log("determinant", "Será calculada a determinante da matriz Y:");
const detY = calculateDeterminant3x3(determinantYMatrix);
log("determinant", "Será calculada a determinante da matriz Z:");
const detZ = calculateDeterminant3x3(determinantZMatrix);

const x = detX / detMain;
const y = detY / detMain;
const z = detZ / detMain;

return [
{ unknown: "x", value: x },
{ unknown: "y", value: y },
{ unknown: "z", value: z },
let determinantsOutput = [
{
unknown: "a",
matrixHTML: mathJaxHTMLWriter.write3x3Matrix(determinantMainMatrix),
result: detMain,
},
{
unknown: "x",
matrixHTML: mathJaxHTMLWriter.write3x3Matrix(determinantXMatrix),
result: detX,
},
{
unknown: "y",
matrixHTML: mathJaxHTMLWriter.write3x3Matrix(determinantYMatrix),
result: detY,
},
{
unknown: "z",
matrixHTML: mathJaxHTMLWriter.write3x3Matrix(determinantZMatrix),
result: detZ,
},
];

let classificationOutput = {
type: "SPD",
message: "Sistema Possível Determinado (SPD) - O sistema uma solução",
};
let messageOutput = "Cálculo realizado com sucesso";

if (isDeterminantEqualsZero(detMain)) {
if (areAllDeterminantsZero([detX, detY, detZ])) {
classificationOutput.type = "SPI";
classificationOutput.message =
"Sistema Possível Indeterminado (SPI) - O sistema tem infinitas soluções";
} else if (hasDeterminantsNotEqualsZero([detX, detY, detZ])) {
classificationOutput.type = "SI";
classificationOutput.message =
"Sistema Impossível (SI) - O sistema não tem solução";
}
const equationResultOutput = {
classification: classificationOutput,
message: messageOutput,
resolutions: [],
determinants: determinantsOutput,
};
return equationResultOutput;
}

const xResult = detX / detMain;
const yResult = detY / detMain;
const zResult = detZ / detMain;

const equationResultOutput = {
classification: classificationOutput,
message: messageOutput,
resolutions: [
{ unknown: "x", value: xResult },
{ unknown: "y", value: yResult },
{ unknown: "z", value: zResult },
],
determinants: determinantsOutput,
};

return equationResultOutput;
}

function extractCoefficients(eq) {
Expand Down
38 changes: 38 additions & 0 deletions src/scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,49 @@ function roundToThreeDecimalPlaces(number) {
*/
const elementExists = (el) => el != null;

/**
* Verifica se um determinante dado é igual a zero.
* @param {number} det O valor do determinante a ser verificado.
* @returns {boolean} Retorna true se o determinante for zero, false caso contrário.
*/
const isDeterminantEqualsZero = (det) => det === 0;

/**
* Verifica se todos os determinantes em um array são iguais a zero.
* @param {number[]} determinants Um array contendo os determinantes a serem verificados.
* @returns {boolean} Retorna true se todos os determinantes forem zero, false caso contrário.
*/
function areAllDeterminantsZero(determinants) {
// Verifica se todos os elementos do array são iguais a zero
return determinants.every((det) => isDeterminantEqualsZero(det));
}

/**
* Verifica se há determinantes dentro de um array que não são iguais a zero.
* @param {number[]} determinants Um array contendo os determinantes a serem verificados.
* @returns {boolean} Retorna true se algum determinante não for zero, false caso contrário.
*/
function hasDeterminantsNotEqualsZero(determinants) {
// Verifica se algum elemento do array não é igual a zero
return determinants.some((det) => det !== 0);
}

/**
* Verifica se um determinante dado não é igual a zero.
* @param {number} det O valor do determinante a ser verificado.
* @returns {boolean} Retorna true se o determinante não for zero, false caso contrário.
*/
const isDeterminantNotEqualsZero = (det) => det !== 0;

export {
isMatrixNxN,
isNumber,
log,
writeMatrix,
elementExists,
roundToThreeDecimalPlaces,
isDeterminantEqualsZero,
isDeterminantNotEqualsZero,
areAllDeterminantsZero,
hasDeterminantsNotEqualsZero,
};
Loading

0 comments on commit 5e371b0

Please sign in to comment.