-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulator.js
335 lines (293 loc) · 8.68 KB
/
simulator.js
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
states{
id,
connectedNodes[],
selected
final
}
connectedNodes{
input: input string,
state: state name
}
*/
let states = [
{
id: 0,
connectedNodes: [],
seleced: false,
final: false,
},
];
$(document).ready(function () {
console_msg(
"Press Add state button to Add a new node in the diagram and drag the node to custom positions"
);
$("#q0").draggable({ containment: ".draw-area" });
// Button functions
// Add Node on button click
$("#add-state").click(function () {
console_msg(
"Inputs and transitions can be defined through state transition button"
);
// Generate a node Id
const nodeId = getNodeId();
let nodeText = `<div
id='q${nodeId}' class='node'>
<p> Q${nodeId} </p>
<p id="q${nodeId}-input-details" class="input-details"></p>
</div>`;
$(".draw-area").append(nodeText);
$(".node").draggable({ containment: ".draw-area" });
states.push({
id: nodeId,
connectedNodes: [],
selected: false,
final: false,
});
});
// Delete node function
$("#del-state").click(function () {
states.forEach((n) => {
if (n.selected) {
$(`#q${n.id}`).remove();
states.splice(n.id, 1);
}
});
});
// Simulate button listener
$("#test-btn").click(() => {
// check if final state is defined
let finalStatePresent = false;
states.forEach((n) => {
if (n.final == true) finalStatePresent = true;
});
if (finalStatePresent) $("#test-form").modal("show");
else
console_msg(
"No Final State Specified in the Diagram. Select a state and press Make Final State",
2
);
});
// Open state transition modal
$("#connect-state").click(() => $("#connect-form").modal("show"));
// Run siimulation listener
$("#run-btn").click(() => {
// reset validation
document.getElementById("input-str-validator").textContent = "";
const inputStr = $("#input-str").val();
if (inputStr == "")
document.getElementById("input-str-validator").textContent =
"Test string cannot be empty";
else {
$("#test-form").modal("hide");
runSimulation(inputStr);
}
});
// Connect states to a node on specified input
$("#add-transition-btn").click(function () {
let frm = $("#from-state").val();
let input = $("#state-input").val();
let to = $("#to-state").val();
frm = frm.toLowerCase();
to = to.toLowerCase();
if (transitionValidated(frm, input, to)) {
// Connect states
$(`#${frm}`).connections({ to: `#${to}` });
$("#connect-form").modal("hide");
// Set up connection details on the node
let inputDetails = document.getElementById(`${frm}-input-details`);
const nodeId = parseInt(frm[1]);
let cNodes = states[nodeId].connectedNodes;
if (cNodes.length == 0) inputDetails.textContent = `${input} -> ${to}`;
else if (cNodes.length > 0)
inputDetails.textContent += ` | ${input} -> ${to}`;
cNodes.push({
input: input,
state: to[1],
});
// Print message on console
console_msg(
`State Transition specified from ${frm} to ${to} for input ${input}`,
1
);
}
});
// Validation for state transition form
function transitionValidated(from, input, to) {
document.getElementById("frm-validate").textContent = ``;
document.getElementById("input-validate").textContent = ``;
document.getElementById("to-validate").textContent = ``;
let fromStatePresent = false,
toStatePresent = false,
inputPresent = false;
const f = from[1];
const i = input;
const t = to[1];
states.forEach((n) => {
if (n.id == f) {
fromStatePresent = true;
if (n.connectedNodes.filter((c) => c.input === i).length)
inputPresent = true;
}
if (n.id == t) {
toStatePresent = true;
}
});
if (!fromStatePresent)
document.getElementById(
"frm-validate"
).textContent = `State ${from} is not present in diagram. Enter a valid state name`;
if (inputPresent)
document.getElementById(
"input-validate"
).textContent = `Specified input ${input} is already defined in the state ${from}`;
if (input == "")
document.getElementById(
"input-validate"
).textContent = `Input cannot be empty filed`;
if (!toStatePresent)
document.getElementById(
"to-validate"
).textContent = `State ${to} is not present in diagram. Enter a valid state name`;
if (fromStatePresent && toStatePresent && !inputPresent && input != "")
return true;
return false;
}
// Function makes the seleced state as final state
$("#final-btn").click(function () {
let finalStateId = null;
states.forEach((n) => {
if (n.selected) {
n.final = true;
finalStateId = n.id;
}
});
const state = document.getElementById(`q${finalStateId}`);
state.style.border = "#1f3c7d 12px solid";
});
// Functions if the node is selected
function nodeCheckClick() {
states.forEach((n) => {
$(`#q${n.id}`)
.mousedown(() => {
n.selected = true;
disSelectAll(n);
})
.mouseup(() => {
$(`#q${n.id}`).connections("update");
});
});
if (states.length < 1) $("#final-btn").hide();
let selected = states.some((n) => n.selected == true);
// Hide make final state button if no state is selected
if (!selected) $("#final-btn").hide();
else $("#final-btn").show();
}
setInterval(nodeCheckClick, 200);
// Diselect other nodes if one is selected
function disSelectAll(selectedNode = 0) {
states.forEach((n) => {
if (n.id != selectedNode.id) n.selected = false;
});
}
// Check select state
setInterval(() => {
states.forEach((n) => {
let color = "#577ee8";
if (n.selected) color = "#abeada";
$(`#q${n.id}`).css("background-color", color);
});
}, 200);
// Generate New Node id
function getNodeId() {
let tmpId = states.length;
// check if the id exists
while (true) {
found = false;
for (let i = 0; i < states.length; i++) {
if (states[i].id == tmpId) {
found = true;
break;
}
}
if (found) tmpId++;
else return tmpId;
}
}
// Run Simulation for a given input str
function runSimulation(inputStr) {
// Path specifies the order in which the inputs move through state
let path = [];
if (states.length == 0) {
console_msg("Draw A diagram to run simulator..", 1);
return;
}
console_msg("Test Running. . .", 2);
document.getElementById("test-string-disp").textContent = inputStr;
// Pointer startes at node zero
let statePtr = states[0].id;
let currentState = states[statePtr]; // Id of the state on which dfa rests
path.push(currentState);
let inputPtr = 0; // Points to the index in input string
let input = null;
while (inputPtr < inputStr.length) {
let nextStateIndex = null;
input = inputStr[inputPtr];
// Find the state transition corrosponding to input
currentState.connectedNodes.forEach((n) => {
if (n.input == input) {
nextStateIndex = n.state;
return;
}
});
// Check if state responds to an input or not
if (nextStateIndex == null) {
console.log(
`Terminated termnated at state ${currentState} for input ${input}`
);
break;
}
console.log("next state Index");
currentState = states[nextStateIndex];
path.push(currentState);
inputPtr++;
}
console.log("sim over..");
console.log("current state: ");
console.log(currentState);
if (currentState.final) {
console.log("Test Passed ....");
console_msg(
`Input String <span style="color: green"> ACCEPTED </span>, input ended at state q${currentState.id}`,
1
);
} else {
console_msg(
'Input string <span style="color: red">REJECTED</span> by DFA.',
1
);
}
console.log("Path");
console.log(path);
for (let i = 0; i < path.length; i++) {
annimate(path, i);
}
}
function annimate(path, i) {
setTimeout(function () {
console.log(path[i]);
}, 2000 * i);
}
// Print Messaages in console
function console_msg(msg, type = 0) {
// type 0: Instruction
// type 1 : Info
// type 2 : Error
let color = "blue";
if (type == 1) color = "#068671";
else if (type == 2) color = "red";
const cons = document.getElementById("msg");
cons.innerHTML = msg;
cons.style.color = color;
}
});