Skip to content

Commit

Permalink
funcionando equivalencia
Browse files Browse the repository at this point in the history
  • Loading branch information
YanGuilherme committed Jul 30, 2024
1 parent 7d82a9e commit fb81ee8
Show file tree
Hide file tree
Showing 4 changed files with 162 additions and 59 deletions.
32 changes: 22 additions & 10 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,16 @@
-Tirar o estado D de onde não precisa (tirar estados inacessiveis)
-FrontEnd para minimizar
-Colocar validacao na entrada da cadeia (vai tratar erros do backend)
PARA FAZER
-Retirar cadeia vazia do AFN
-Renomear os automatos
-Adicionar entrada de cadeia vazia nos AFN (tem que tirar ela antes de converter para AFD)
-Equivalencia entre automatos
-Fazer metodo para gerar todas as cadeias possiveis
-Fazer um modal para selecionar quais automatos a partir dos salvos vc quer testar equivalencia
-Fazer testes faceis de comparacao antes de realizar o teste de palavras nos dois
PARA FAZER
-Retirar cadeia vazia do AFN
-Adicionar entrada de cadeia vazia nos AFN (tem que tirar ela antes de converter para AFD)
-
-Construir um AFN a partir de uma regex
-->
Expand Down Expand Up @@ -46,14 +47,20 @@ <h1>AutomaTop</h1>
<h2>Formulário de entrada</h2>
<form id="entrada_form">
<button id="btn_reset" type="button" disabled>Reset</button>
<h3>Escolha o nome do autômato</h3>
<input type="text" name="nome_automato" id="entrada_nome" placeholder="Insira o nome do autômato" >
<button id="btn_inserir_nome">Escolher</button>
<div id="container_nome"></div>


<h3>Escolha o tipo do autômato</h3>
<select name="tipo_automato" id="select_tipo">
<select name="tipo_automato" id="select_tipo" disabled>
<option value="AFD" selected>AFD</option>
<option value="AFN">AFN</option>
</select>
<h3>Digite a quantidade de estados do autômato</h3>
<input type="number" name="quantidade_estados" id="quantidade_estados" placeholder="Insira a quantidade">
<button id="btn_inserir_estados">Inserir</button>
<input disabled type="number" name="quantidade_estados" id="quantidade_estados" placeholder="Insira a quantidade">
<button disabled id="btn_inserir_estados">Inserir</button>
<div id="container_estados"></div>
<h3>Digite o alfabeto que será utilizado</h3>
<input type="text" name="alfabeto" id="entrada_alfabeto" placeholder="Insira o alfabeto" disabled>
Expand Down Expand Up @@ -92,10 +99,15 @@ <h3>Autômatos minimizados</h3>

<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">&times;</span>
<!-- Conteúdo do modal -->
<h2>Selecione um Autômato</h2>
<select id="automatoSelect">
<!-- Opções serão preenchidas aqui -->
</select>
<button id="saveButton">Testar</button>
<div id="container_resultado"></div>
</div>
</div>
</div>

</main>


Expand Down
74 changes: 40 additions & 34 deletions scriptForm.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
document.addEventListener('DOMContentLoaded', function(){

const input_nome = document.getElementById('entrada_nome');
const botao_escolher_nome = document.getElementById('btn_inserir_nome');
const container_nome = document.getElementById('container_nome');

const select_tipo_automato = document.getElementById('select_tipo');

const input_quantidade = document.getElementById('quantidade_estados');
Expand Down Expand Up @@ -32,6 +36,7 @@ document.addEventListener('DOMContentLoaded', function(){

//variaveis que serao a 5-upla do automato
let automatoForm = {
nome: '',
tipo : '',
estados : [],
alfabeto_array : [],
Expand All @@ -46,6 +51,28 @@ document.addEventListener('DOMContentLoaded', function(){
botao_reset.disabled = true; //desabilita o botao
});

botao_escolher_nome.addEventListener('click', function(event){
event.preventDefault();
const nome_entrada = input_nome.value;
if(nome_entrada != ''){
automatoForm.nome = nome_entrada;
select_tipo_automato.disabled = false;
input_quantidade.disabled = false;
botao_inserir_estados.disabled = false;
input_nome.disabled = true;
botao_escolher_nome.disabled = true;
botao_reset.disabled = false;
container_nome.innerHTML = `Nome escolhido: <strong>${nome}</strong>`;

}else{
select_tipo_automato.disabled = true;
input_quantidade.disabled = true;
botao_inserir_estados.disabled = true;
alert("Por favor insira um nome válido.");

}
});


botao_inserir_estados.addEventListener('click', function(event){
event.preventDefault();
Expand All @@ -54,7 +81,6 @@ document.addEventListener('DOMContentLoaded', function(){
const quantidade_estados = input_quantidade.value;

if(quantidade_estados > 0){
botao_reset.disabled = false;

input_quantidade.disabled = true;
botao_inserir_estados.disabled = true;
Expand All @@ -70,7 +96,7 @@ document.addEventListener('DOMContentLoaded', function(){
for(let i = 0 ; i < quantidade_estados ; i++){
automatoForm.estados.push(`q${i}`);
const estado_msg = document.createElement('p');
estado_msg.textContent = `Estado ${i+1} inserido: q${i}.`;
estado_msg.innerHTML += `Estado ${i+1} inserido: <strong>q${i}</strong>.`;
estados_container.appendChild(estado_msg);
}
console.log(automatoForm.estados);
Expand All @@ -94,7 +120,7 @@ document.addEventListener('DOMContentLoaded', function(){
if (invalidSymbols.length > 0) {
alert('Por favor, insira apenas caracteres únicos separados por espaços.');
} else {
console.log(`Alfabeto inserido ${automatoForm.alfabeto_array}`);
console.log(`<strong>Alfabeto inserido ${automatoForm.alfabeto_array}</strong>`);

// lógica para enviar o alfabeto para o backend aqui

Expand All @@ -107,7 +133,7 @@ document.addEventListener('DOMContentLoaded', function(){

for(const letra of automatoForm.alfabeto_array){
const alfabeto_msg = document.createElement('p');
alfabeto_msg.textContent = `Símbolo adicionado: ${letra}`;
alfabeto_msg.innerHTML = `Símbolo adicionado: <strong>${letra}</strong>`;
alfabeto_container.appendChild(alfabeto_msg);
}

Expand All @@ -125,33 +151,26 @@ document.addEventListener('DOMContentLoaded', function(){
automatoForm.tipo = select_tipo_automato.value;

const transicoesInput = document.querySelectorAll('.transicao_input');
//let transicoesValidas = true;

transicoesInput.forEach(input => {
const [estadoAtual, simbolo] = input.name.split('_');
const selected_options = Array.from(input.selectedOptions).map(option => option.value);
if(automatoForm.tipo === 'AFD'){
automatoForm.transicoes.set(`${estadoAtual}_${simbolo}`, selected_options[0]);

}else{
if(selected_options.length === 0 || selected_options[0] === ''){
transicoesValidas = false;
} else {
automatoForm.transicoes.set(`${estadoAtual}_${simbolo}`, selected_options[0]);
}
} else if(automatoForm.tipo === 'AFN'){
const chave = `${estadoAtual}_${simbolo}`;
automatoForm.transicoes.set(chave, selected_options);
}

// if(automatoForm.tipo === 'AFD'){
// if(selected_options.length === 0 || selected_options[0] === ''){
// transicoesValidas = false;
// } else {
// automatoForm.transicoes.set(`${estadoAtual}_${simbolo}`, selected_options[0]);
// }
// } else if(automatoForm.tipo === 'AFN'){
// const chave = `${estadoAtual}_${simbolo}`;
// automatoForm.transicoes.set(chave, selected_options);
// }
});

console.log(mapTransicoes())
const transicao_msg = document.createElement('p');
transicao_msg.textContent = 'Transições inseridas com sucesso.';
transicao_msg.innerHTML = '<strong>Transições inseridas com sucesso.</strong>';
form_transicoes_container.style.display = 'none';
transicoes_container.appendChild(transicao_msg);

Expand All @@ -161,21 +180,7 @@ document.addEventListener('DOMContentLoaded', function(){
gerarEstadosAceitacao();


// if(!transicoesValidas && automatoForm.tipo === 'AFD'){
// alert('Por favor, selecione um estado de destino para cada transição no AFD.');
// } else {
// console.log(mapTransicoes())
// const transicao_msg = document.createElement('p');
// transicao_msg.textContent = 'Transições inseridas com sucesso.';
// form_transicoes_container.style.display = 'none';
// transicoes_container.appendChild(transicao_msg);


// botao_inserir_transicoes.disabled = true;
// gerarEstadoInicial();
// gerarEstadosAceitacao();

// }
});
function mapTransicoes() {
const transicoes_formatadas = {};
Expand All @@ -202,7 +207,7 @@ document.addEventListener('DOMContentLoaded', function(){
return it.length > 0;
});
return estadosDestino;
}
}

function gerarFormularioTransicoes(){
form_transicoes_container.innerHTML = '';
Expand Down Expand Up @@ -331,6 +336,7 @@ document.addEventListener('DOMContentLoaded', function(){
function gerarJSON(){
const transicoes_formatadas = mapTransicoes();
const automato = {
"nome": automatoForm.nome,
"tipo": automatoForm.tipo,
"estadoInicial": automatoForm.estadoInicial,
"estadosAceitacao": automatoForm.estadosAceitacao,
Expand Down
102 changes: 88 additions & 14 deletions scriptPainel.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

async function buscarTodosAutomatos(){
try {
const response = await fetch('http://localhost:8080/api/automatos/findAll');
Expand All @@ -6,6 +7,8 @@ async function buscarTodosAutomatos(){
}
const automatos = await response.json();
exibirAutomatos(automatos);
return automatos;

} catch (error) {
console.error('Erro ao buscar autômatos:', error);
}
Expand All @@ -22,8 +25,9 @@ function exibirAutomatos(automatos) {
automato_container.id = `${automato.id}`;
automato_container.className = 'element_automato';

const id_automato = document.createElement('p');
id_automato.textContent = `${automato.id}`;
const rotulo_automato = document.createElement('p');
rotulo_automato.className = 'rotulo_automato';
rotulo_automato.innerHTML = `${automato.nome}`;

const botao_cadeia = document.createElement('button');
botao_cadeia.textContent = 'Testar';
Expand Down Expand Up @@ -58,10 +62,10 @@ function exibirAutomatos(automatos) {
const botao_equivalencia = document.createElement('button');
botao_equivalencia.textContent = 'Testar equivalência';
botao_equivalencia.addEventListener('click', () => {
testar_equivalencia(automato);
modal_equivalencia(automato);
});

automato_container.appendChild(id_automato);
automato_container.appendChild(rotulo_automato);
automato_container.appendChild(botao_cadeia);
automato_container.appendChild(botao_detalhes);

Expand All @@ -86,18 +90,88 @@ function exibirAutomatos(automatos) {
});
}

async function testar_equivalencia(automato) {
let modal = document.getElementById("myModal");
modal.style.display = "block";
async function testar_equivalencia(id1, id2){
try {
const response = await fetch(`http://localhost:8080/api/automatos/testarEquivalencia/${id1}/${id2}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const resposta = await response.json();
return resposta;

} catch (error) {
console.error('Erro ao testar equivalencia:', error);
}
}

// Fechar o modal quando o usuário clicar no "x"
let span = document.getElementsByClassName("close")[0];
span.onclick = function() {
async function modal_equivalencia(automato) {

let modal = document.getElementById("myModal");
modal.style.display = "none";
let container_resultado = document.getElementById("container_resultado");

modal.style.display = "block";

const lista_automatos = await buscarTodosAutomatos();

let select = document.getElementById("automatoSelect");

select.innerHTML = ''; // Limpar opções existentes
container_resultado.innerHTML = '';

lista_automatos.forEach(a => {
if (a.id !== automato.id) {
const option = document.createElement("option");
option.value = a.id;
option.text = `${a.nome} - Tipo: ${a.tipo}`;
select.appendChild(option);
}
});
let saveButton = document.getElementById("saveButton");

if (saveButton) {
saveButton.onclick = async function() {
container_resultado.innerHTML = '';
const select = document.getElementById("automatoSelect");
const selectedId = select.value;
const resposta_teste = await testar_equivalencia(automato.id, selectedId);

const exibir_resposta = document.createElement("p");
const exibir_resposta_final = document.createElement("p");

let validacao_final = false;

resposta_teste.forEach(resposta => {
exibir_resposta.innerHTML +=
`<strong>Tipo de teste: </strong> ${resposta.nome}<br>
<strong>Resultado: </strong>${resposta.message}<br><br>
`;
validacao_final = resposta.sucesso;

});
if(validacao_final){
exibir_resposta_final.className = 'aceita_cadeia';
exibir_resposta_final.textContent = 'Equivalentes';
}else{
exibir_resposta_final.className = 'rejeita_cadeia';
exibir_resposta_final.textContent = 'Não equivalentes'
}


container_resultado.appendChild(exibir_resposta);
container_resultado.appendChild(exibir_resposta_final);

};

}


}






// Fechar o modal quando o usuário clicar fora dele
window.onclick = function(event) {
let modal = document.getElementById("myModal");
Expand Down Expand Up @@ -314,13 +388,14 @@ function toggleDetalhesAutomato(automato, container, botao){

const detalhes_automato = `
<div id="automato-container-${automato.id}"></div>
<pre><strong>Nome:</strong> ${automato.nome}</pre>
<pre><strong>Tipo:</strong> ${automato.tipo}</pre>
<pre style="white-space: pre-wrap;"><strong>Estados <i>Q</i>:</strong> ${automato.estados.join(', ')}</pre>
<pre><strong>Alfabeto Σ:</strong> ${automato.alfabeto.join(', ')}</pre>
<pre><strong>Transições:</strong></pre>
<pre>${formatarTransicoesComoTabela(automato.transicoes,automato)}</pre>
<pre><strong>Estado inicial:</strong> ${automato.estadoInicial}</pre>
<pre style="white-space: pre-wrap;"><strong>Estados de aceitação:</strong> ${automato.estadosAceitacao.join(', ')}</pre>
<pre style="white-space: pre-wrap;"><strong>Estados de aceitação: </strong> ${automato.estadosAceitacao.join(', ')}</pre>
`;
new_detalhes_container.innerHTML = detalhes_automato;

Expand Down Expand Up @@ -364,7 +439,6 @@ async function renderAutomatos(automato) {

// Renderizar o gráfico usando viz.js
const viz = new Viz();
console.log(dotCode);
viz.renderSVGElement(dotCode)
.then(svgElement => {
automatoContainer.appendChild(svgElement);
Expand Down Expand Up @@ -404,4 +478,4 @@ async function deletar(automato){

document.addEventListener('DOMContentLoaded', (event) => {
buscarTodosAutomatos();
});
});
Loading

0 comments on commit fb81ee8

Please sign in to comment.