Simulate nondeterministic automatons

This commit is contained in:
2024-03-05 21:28:53 +01:00
parent bc3cac2460
commit b0dd188d52
3 changed files with 51 additions and 30 deletions

View File

@@ -47,7 +47,7 @@ export function openAutomaton(states, editable = false) {
*/
function updateUIState() {
wordInput.value = builder;
if (state === -1 || states.length === 0 || !states[state].accepting) {
if (typeof Array.from(state).find((state) => states[state].accepting) === 'undefined') {
light.classList.remove(IS_VALID);
light.classList.add(IS_INVALID);
} else {
@@ -55,8 +55,10 @@ export function openAutomaton(states, editable = false) {
light.classList.add(IS_VALID);
}
graph.forEach((node) => node.active = false);
if (state in graph.nodes) {
graph.nodes[state].active = true;
for (const s of state) {
if (s in graph.nodes) {
graph.nodes[s].active = true;
}
}
viewer.restart();
}
@@ -79,11 +81,16 @@ export function openAutomaton(states, editable = false) {
* @param {string} letter
*/
function step(letter) {
if (state === -1) {
return;
}
/** @type {number[]} */
const newStates = [];
builder += letter;
state = states[state].transitions[letter] ?? -1;
for (const s of state) {
if (s in states) {
const transitions = states[s].transitions[letter];
newStates.push(...transitions);
}
}
state = newStates;
updateUIState();
}
@@ -126,8 +133,17 @@ export function openAutomaton(states, editable = false) {
/**
* @param {import('./examples.js').State[]} states
* @returns {number[]}
*/
function findStart(states) {
let state = states.findIndex(state => state.start);
return Math.max(state, 0);
const starts = [];
for (let i = 0; i < states.length; i++) {
if (states[i].start) {
starts.push(i);
}
}
if (starts.length === 0) {
starts.push(0);
}
return starts;
}