-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
279 lines (234 loc) · 11 KB
/
index.html
File metadata and controls
279 lines (234 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Решение систем уравнений</title>
</head>
<body>
<div class="equation-rules">
<h2>Правила ввода уравнений</h2>
<ol>
<li>Все переменные должны быть записаны в левой части.</li>
<li>Переменные сортируются по алфавиту и индексам.</li>
<li>Примеры уравнений: "x+2*y+5z=6", "4*x2 + 5x1 + x3 = 6"(после переменных находятся индексы)</li>
</ol>
</div>
<form id="equationForm">
<button type="button" onclick="addEquation()">Добавить уравнение</button>
<button type="button" onclick="solveEquations()">Решить</button>
<br/>
<label for="equations">Введите систему уравнений:</label>
<div id="equations">
<div class="equation">
<input type="text" name="equation[]" placeholder="Уравнение" style="width: 30%;">
<button type="button" onclick="removeEquation(this)">Удалить</button>
</div>
<div class="equation">
<input type="text" name="equation[]" placeholder="Уравнение" style="width: 30%;">
<button type="button" onclick="removeEquation(this)">Удалить</button>
</div>
</div>
</form>
<br/>
<div id="output"></div>
</body>
<script>
function addEquation() {
const equationsDiv = document.getElementById('equations');
const newEquation = document.createElement('div');
newEquation.className = 'equation';
newEquation.innerHTML = '<input type="text" name="equation[]" placeholder="Уравнение" style="width: 30%;"> <button type="button" onclick="removeEquation(this)">Удалить</button>';
equationsDiv.appendChild(newEquation);
}
function removeEquation(button) {
const equationDiv = button.parentElement;
equationDiv.remove();
}
function collectEquations() {
const equations = [];
const inputs = document.querySelectorAll('input[name="equation[]"]');
inputs.forEach(input => {
if (input.value.trim() !== '') {
equations.push(input.value.replaceAll(' ', '').replaceAll('*', ''));
}
});
console.log(equations);
return equations; // Возвращаем false, чтобы предотвратить отправку формы
}
function parseEquations(equations) {
const variableSet = new Set();
const coefficients = [];
// Разбиваем каждое уравнение
for (let eq of equations) {
const parts = eq.split('=');
const leftSide = parts[0].trim();
const rightSide = parts[1].trim();
// Получаем свободный член (правую часть)
let freeTerm = eval(rightSide); // Оценка выражения, содержащего числа и оператор +
const row = {}; // Объект для коэффициентов переменных в данном уравнении
// Парсим левую часть (коэффициенты переменных)
const terms = leftSide.match(/([+-]?\d*\.*\d*)?\s*([a-zA-Z_]\w*)/g);
for (let term of terms) {
const match = term.match(/([+-]?\d*\.*\d*)?\s*([a-zA-Z_]\w*)/);
console.log(match);
if (!match[1]) match[1] = 1; // Если коэффициент не указан, подразумеваем 1
if (match[1] == '+' || match[1] == '-') match[1] += 1
const coeff = parseFloat(match[1]);
const variable = match[2];
// Убираем автоматическую обработку знака
row[variable] = coeff;
variableSet.add(variable);
}
coefficients.push({ left: row, right: freeTerm });
}
let variables = customSort(Array.from(variableSet));
return { coefficients, variables: variables};
}
function customSort(variables) {
variables.sort((a, b) => {
// Разделяем буквы и числа
const [varA, numA] = a.match(/([a-zA-Z]+)(\d*)/).slice(1);
const [varB, numB] = b.match(/([a-zA-Z]+)(\d*)/).slice(1);
// Сравниваем буквы
if (varA === varB) {
// Если буквы одинаковые, сравниваем числовые суффиксы
return (numA ? parseInt(numA) : 0) - (numB ? parseInt(numB) : 0);
}
return varA.localeCompare(varB);
});
return variables;
}
function buildMainMatrix(data) {
let matrix = [];
for (let r = 0; r < data.coefficients.length; r++) {
let row = [];
for (let i = 0; i < data.variables.length; i++) {
let coeff = data.coefficients[r].left[data.variables[i]];
if (!coeff) coeff = 0;
row.push(coeff);
}
matrix.push(row);
}
return matrix;
}
function buildMainMatrix(data) {
let matrix = [];
for (let r = 0; r < data.coefficients.length; r++) {
let row = [];
for (let i = 0; i < data.variables.length; i++) {
let coeff = data.coefficients[r].left[data.variables[i]];
if (!coeff) coeff = 0;
row.push(coeff);
}
matrix.push(row);
}
return matrix;
}
function buildMatrix(data, col) {
let matrix = [];
for (let r = 0; r < data.coefficients.length; r++) {
let row = [];
for (let i = 0; i < data.variables.length; i++) {
if (i === col) {
let freeTerm = data.coefficients[r].right;
row.push(freeTerm);
} else {
let coeff = data.coefficients[r].left[data.variables[i]];
if (!coeff) coeff = 0;
row.push(coeff);
}
}
matrix.push(row);
}
return matrix;
}
function solve(data) {
let matrix = buildMainMatrix(data)
const mainDet = calculateDeterminant(matrix);
if (mainDet === 0 || data.coefficients.length != data.variables.length) {
return null; // Система имеет бесконечно много решений или нет решений
}
const solutions = {};
const steps1 = [{name: `Определитель D =`, matrix, text: `= ${mainDet}`}];
const steps2 = [`Определитель D = ${mainDet}`];
for (let i = 0; i < data.variables.length; i++) {
matrix = buildMatrix(data, i)
const detX = calculateDeterminant(matrix);
const value = detX / mainDet;
solutions[data.variables[i]] = value;
steps1.push({name: `Определитель D_${data.variables[i]} =`, matrix, text: `= ${detX}`});
steps2.push(`${data.variables[i]} = D_${data.variables[i]} / D = ${value}`);
}
return { solutions, steps1, steps2 };
}
function calculateDeterminant(matrix) {
const size = matrix.length;
if (size === 2) {
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
}
let det = 0;
for (let i = 0; i < size; i++) {
const subMatrix = matrix.slice(1).map(row => row.filter((_, j) => j !== i));
det += (matrix[0][i] * calculateDeterminant(subMatrix)) * (i % 2 === 0 ? 1 : -1);
}
console.log(det);
return det;
}
function displayOutput(solution) {
const outputDiv = document.getElementById('output');
outputDiv.innerHTML = '';
if (!solution) {
outputDiv.innerHTML = "Система уравнений не имеет единственного решения.";
return;
}
for (let i = 0; i < solution.steps1.length; i++) {
outputDiv.innerHTML += solution.steps1[i].name;
outputDiv.innerHTML += drawMatrix(solution.steps1[i].matrix);
outputDiv.innerHTML += solution.steps1[i].text + '<br>';
outputDiv.innerHTML += solution.steps2[i] + '<br><br>';
}
outputDiv.innerHTML += '<br>Решение: ' +
Object.entries(solution.solutions)
.map(([varName, value]) => `${varName} = ${value}`)
.join(', ');
}
function drawMatrix(matrix) {
let matrixHTML = '<div class="matrix">';
matrix.forEach((row) => {
matrixHTML += '<div class="row">';
row.forEach((value) => {
matrixHTML += `<div class="cell">${value}</div>`;
});
matrixHTML += '</div>';
});
matrixHTML += '</div>';
return matrixHTML;
}
function solveEquations() {
const equations = collectEquations();
const result = parseEquations(equations);
const solution = solve(result);
displayOutput(solution);
}
</script>
<style>
.matrix {
display: inline-block;
margin: 10px;
border: 1px solid #000;
}
.row {
display: flex;
}
.cell {
width: 30px;
height: 30px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
font-size: 14px;
}
</style>
</html>