JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Determinante de uma matriz</h1>
<form id="form_ordem_matriz" action="#">
<label for="ordem">Informe a ordem da matriz:</label>
<input type="text" id="ordem" maxlength="2">
</form>
<form id="form_matriz" action="#">
<div id="matriz">
<!--
<input type="text" class="elemento_matriz">
<input type="text" class="elemento_matriz">
<input type="text" class="elemento_matriz"><div></div>
<input type="text" class="elemento_matriz">
<input type="text" class="elemento_matriz">
<input type="text" class="elemento_matriz"><div></div>
-->
</div>
<button id="calcular_determinante" type="button">Calcular determinante</button>
<div id="resultado"></div>
</form>
CSS
body {
margin: 0;
padding: 20px
}
body, input, button {
font: 13px Verdana, Arial, sans-serif
}
h1 {
margin: 0 0 10px 0;
padding: 0;
font-size: 18px;
color: #133572
}
input[type=text] {
border: 1px solid #CCC
}
#ordem {
width: 30px;
text-align: right
}
#matriz {
margin: 20px 0
}
.elemento_matriz {
width: 30px;
height: 20px;
margin: 0 10px 10px 0
}
#calcular_determinante {
margin: 20px 0;
display: none
}
JavaScript
// Gerar matriz
document.forms.form_ordem_matriz.onsubmit = function(e) {
e.preventDefault();
var ordem = parseInt(document.getElementById('ordem').value, 10),
html_matriz = '';
if (isNaN(ordem) || ordem < 1) {
alert('Informe um número \u2265 1');
document.getElementById('ordem').select();
return;
}
for (var i = 0; i < ordem; i++) {
for (var j = 0; j < ordem; j++) {
html_matriz += '<input type="text" class="elemento_matriz">';
}
html_matriz += '<div></div>';
}
document.getElementById('matriz').innerHTML = html_matriz;
document.getElementById('calcular_determinante').style.display = 'block';
}
// Calcular determinante
document.getElementById('calcular_determinante').onclick = function() {
// Colocar matriz na variável
var matriz = [],
campos = document.getElementsByClassName('elemento_matriz'),
ordem = Math.sqrt(document.getElementsByClassName('elemento_matriz').length);
for (var i = 0; i < ordem; i++) {
matriz[i] = [];
for (var j = 0; j < ordem; j++) {
matriz[i][j] = parseInt(campos[ordem * i + j].value, 10);
}
}
document.getElementById('resultado').innerHTML = 'Determinante: ' + determinante(matriz);
}
function determinante(a) {
var ordem = a.length;
if (ordem === 1) {
return a[0][0];
}
if (ordem === 2) {
return a[0][0] * a[1][1] - a[0][1] * a[1][0];
}
var...