-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1058 lines (990 loc) · 32.1 KB
/
script.js
File metadata and controls
1058 lines (990 loc) · 32.1 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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Tab switching functionality
function switchTab(tabName) {
// Hide all tab contents
document.querySelectorAll(".tab-content").forEach((content) => {
content.classList.remove("active");
});
// Remove active class from all tab buttons
document.querySelectorAll(".tab-button").forEach((button) => {
button.classList.remove("active");
});
// Show selected tab content
document.getElementById(tabName + "-tab").classList.add("active");
// Add active class to clicked button
event.target.classList.add("active");
}
const visOptions = {
layout: { improvedLayout: true },
physics: { enabled: false },
nodes: {
font: { size: 16, face: "Roboto Mono" },
},
edges: {
font: { size: 14, face: "Roboto Mono" },
},
};
let inputGraph, outputGraph;
let currentSteps = [],
currentExplanations = [],
outputStates = [];
let stepIndex = 0;
let currentExample = null;
let currentConversionType = "";
const examples = {
"nfa-dfa": {
"Binary strings ending with 01": {
states: ["q0", "q1", "q2"],
alphabet: ["0", "1"],
transitions: {
q0: { 0: ["q0", "q1"], 1: ["q0"] },
q1: { 1: ["q2"] },
q2: {},
},
startState: "q0",
finalStates: ["q2"],
description: "Accepts binary strings ending with '01'",
},
"Contains substring 101": {
states: ["q0", "q1", "q2", "q3"],
alphabet: ["0", "1"],
transitions: {
q0: { 0: ["q0"], 1: ["q0", "q1"] },
q1: { 0: ["q2"] },
q2: { 1: ["q3"] },
q3: { 0: ["q3"], 1: ["q3"] },
},
startState: "q0",
finalStates: ["q3"],
description: "Accepts strings containing substring '101'",
},
"Strings starting with 1": {
states: ["q0", "q1", "q2"],
alphabet: ["0", "1"],
transitions: {
q0: { 1: ["q1"], 0: ["q2"] },
q1: { 0: ["q1"], 1: ["q1"] },
q2: {},
},
startState: "q0",
finalStates: ["q1"],
description: "Accepts strings starting with '1'",
},
"Even number of 0s": {
states: ["q0", "q1"],
alphabet: ["0", "1"],
transitions: {
q0: { 0: ["q1"], 1: ["q0"] },
q1: { 0: ["q0"], 1: ["q1"] },
},
startState: "q0",
finalStates: ["q0"],
description: "Accepts strings with even number of 0s",
},
"Epsilon transitions example": {
states: ["q0", "q1", "q2", "q3"],
alphabet: ["a", "b"],
transitions: {
q0: { ε: ["q1"], a: ["q2"] },
q1: { b: ["q3"] },
q2: { a: ["q3"] },
q3: {},
},
startState: "q0",
finalStates: ["q3"],
description: "NFA with epsilon transitions",
},
},
"dfa-nfa": {
"Simple DFA - Even 0s": {
states: ["A", "B"],
alphabet: ["0", "1"],
transitions: {
A: { 0: ["B"], 1: ["A"] },
B: { 0: ["A"], 1: ["B"] },
},
startState: "A",
finalStates: ["A"],
description: "DFA accepting even number of 0s",
},
"DFA - Ends with 10": {
states: ["q0", "q1", "q2"],
alphabet: ["0", "1"],
transitions: {
q0: { 0: ["q0"], 1: ["q1"] },
q1: { 0: ["q2"], 1: ["q1"] },
q2: { 0: ["q0"], 1: ["q1"] },
},
startState: "q0",
finalStates: ["q2"],
description: "DFA accepting strings ending with '10'",
},
"DFA - Divisible by 3": {
states: ["s0", "s1", "s2"],
alphabet: ["0", "1"],
transitions: {
s0: { 0: ["s0"], 1: ["s1"] },
s1: { 0: ["s2"], 1: ["s0"] },
s2: { 0: ["s1"], 1: ["s2"] },
},
startState: "s0",
finalStates: ["s0"],
description: "DFA for binary numbers divisible by 3",
},
"DFA - Contains 11": {
states: ["p0", "p1", "p2"],
alphabet: ["0", "1"],
transitions: {
p0: { 0: ["p0"], 1: ["p1"] },
p1: { 0: ["p0"], 1: ["p2"] },
p2: { 0: ["p2"], 1: ["p2"] },
},
startState: "p0",
finalStates: ["p2"],
description: "DFA accepting strings containing '11'",
},
"DFA - Odd length": {
states: ["even", "odd"],
alphabet: ["0", "1"],
transitions: {
even: { 0: ["odd"], 1: ["odd"] },
odd: { 0: ["even"], 1: ["even"] },
},
startState: "even",
finalStates: ["odd"],
description: "DFA accepting strings of odd length",
},
},
"re-dfa": {
"RE: (0+1)*01": {
regex: "(0+1)*01",
description: "Regular expression for strings ending with '01'",
},
"RE: 1(0+1)*": {
regex: "1(0+1)*",
description: "Regular expression for strings starting with '1'",
},
"RE: (00+11)*": {
regex: "(00+11)*",
description: "Regular expression for strings with even blocks",
},
"RE: 0*1*": {
regex: "0*1*",
description: "Regular expression for 0s followed by 1s",
},
"RE: (0+1)*101(0+1)*": {
regex: "(0+1)*101(0+1)*",
description: "Regular expression containing '101'",
},
},
"re-nfa": {
"RE: a*b+": {
regex: "a*b+",
description: "Zero or more 'a's followed by one or more 'b's",
},
"RE: (a+b)*abb": {
regex: "(a+b)*abb",
description: "Any string ending with 'abb'",
},
"RE: a+b*a": {
regex: "a+b*a",
description: "One or more 'a's, zero or more 'b's, then 'a'",
},
"RE: (ab+ba)*": {
regex: "(ab+ba)*",
description: "Zero or more occurrences of 'ab' or 'ba'",
},
"RE: a(a+b)*b": {
regex: "a(a+b)*b",
description: "Starts with 'a', ends with 'b'",
},
},
"nfa-re": {
"Simple NFA 1": {
states: ["q0", "q1"],
alphabet: ["a", "b"],
transitions: {
q0: { a: ["q0"], b: ["q1"] },
q1: { b: ["q1"] },
},
startState: "q0",
finalStates: ["q1"],
description: "NFA to convert to regular expression",
},
"Simple NFA 2": {
states: ["p0", "p1", "p2"],
alphabet: ["0", "1"],
transitions: {
p0: { 0: ["p1"], 1: ["p0"] },
p1: { 1: ["p2"] },
p2: { 0: ["p2"], 1: ["p2"] },
},
startState: "p0",
finalStates: ["p2"],
description: "Three-state NFA for RE conversion",
},
"NFA with loops": {
states: ["s0", "s1"],
alphabet: ["x", "y"],
transitions: {
s0: { x: ["s0", "s1"], y: ["s0"] },
s1: { y: ["s1"] },
},
startState: "s0",
finalStates: ["s1"],
description: "NFA with self-loops",
},
"Complex NFA": {
states: ["r0", "r1", "r2", "r3"],
alphabet: ["a", "b"],
transitions: {
r0: { a: ["r1"], b: ["r0"] },
r1: { a: ["r2"], b: ["r1"] },
r2: { a: ["r3"], b: ["r2"] },
r3: { a: ["r3"], b: ["r3"] },
},
startState: "r0",
finalStates: ["r3"],
description: "Four-state NFA for complex RE",
},
"Epsilon NFA": {
states: ["t0", "t1", "t2"],
alphabet: ["a", "b"],
transitions: {
t0: { ε: ["t1"], a: ["t0"] },
t1: { b: ["t2"] },
t2: { ε: ["t0"] },
},
startState: "t0",
finalStates: ["t2"],
description: "NFA with epsilon transitions",
},
},
"dfa-re": {
"Two-state DFA": {
states: ["A", "B"],
alphabet: ["0", "1"],
transitions: {
A: { 0: ["B"], 1: ["A"] },
B: { 0: ["A"], 1: ["B"] },
},
startState: "A",
finalStates: ["B"],
description: "Simple two-state DFA",
},
"Three-state DFA": {
states: ["X", "Y", "Z"],
alphabet: ["a", "b"],
transitions: {
X: { a: ["Y"], b: ["X"] },
Y: { a: ["Z"], b: ["Y"] },
Z: { a: ["X"], b: ["Z"] },
},
startState: "X",
finalStates: ["Z"],
description: "Three-state cyclic DFA",
},
"DFA for mod 3": {
states: ["0", "1", "2"],
alphabet: ["0", "1"],
transitions: {
0: { 0: ["0"], 1: ["1"] },
1: { 0: ["2"], 1: ["0"] },
2: { 0: ["1"], 1: ["2"] },
},
startState: "0",
finalStates: ["0"],
description: "DFA for numbers divisible by 3",
},
"String pattern DFA": {
states: ["q0", "q1", "q2", "q3"],
alphabet: ["a", "b"],
transitions: {
q0: { a: ["q1"], b: ["q0"] },
q1: { a: ["q1"], b: ["q2"] },
q2: { a: ["q3"], b: ["q0"] },
q3: { a: ["q1"], b: ["q2"] },
},
startState: "q0",
finalStates: ["q3"],
description: "DFA recognizing pattern 'aba'",
},
"Alternating DFA": {
states: ["even", "odd"],
alphabet: ["x"],
transitions: {
even: { x: ["odd"] },
odd: { x: ["even"] },
},
startState: "even",
finalStates: ["even"],
description: "DFA for even number of x's",
},
},
"cfg-pda": {
"CFG: S → aSb | ε": {
productions: ["S → aSb", "S → ε"],
description: "Context-free grammar for a^n b^n",
},
"CFG: Palindromes": {
productions: ["S → aSa", "S → bSb", "S → a", "S → b", "S → ε"],
description: "CFG for palindromes over {a,b}",
},
"CFG: Balanced parentheses": {
productions: ["S → (S)", "S → SS", "S → ε"],
description: "CFG for balanced parentheses",
},
"CFG: Arithmetic expressions": {
productions: [
"E → E+T",
"E → T",
"T → T*F",
"T → F",
"F → (E)",
"F → id",
],
description: "CFG for arithmetic expressions",
},
"CFG: Nested structures": {
productions: ["S → aSbS", "S → bSaS", "S → ε"],
description: "CFG for nested a's and b's",
},
},
};
function drawGraph(containerId, automaton, isOutput = false) {
const nodes = new vis.DataSet();
const edges = new vis.DataSet();
if (!automaton || !automaton.states || automaton.states.length === 0) {
const container = document.getElementById(containerId);
container.innerHTML =
'<div class="flex items-center justify-center h-full text-gray-500">No automaton to display</div>';
return null;
}
// Add invisible start reference node
nodes.add({ id: "start_ref", hidden: true, physics: false, x: -100, y: 0 });
// Add states
automaton.states.forEach((state, index) => {
const isFinal = automaton.finalStates?.includes(state);
const isStart = state === automaton.startState;
nodes.add({
id: state,
label: state,
shape: "circle",
color: {
background: isStart ? "#dbeafe" : "#ffffff",
border: isFinal ? "#ec4899" : isOutput ? "#3b82f6" : "#10b981",
},
borderWidth: isFinal ? 4 : 2,
font: { size: 16, color: "#1f2937" },
});
// Add start arrow
if (isStart) {
edges.add({
from: "start_ref",
to: state,
arrows: "to",
color: isOutput ? "#3b82f6" : "#10b981",
width: 2,
});
}
});
// Add transitions
if (automaton.transitions) {
Object.entries(automaton.transitions).forEach(([from, trans]) => {
Object.entries(trans).forEach(([symbol, destinations]) => {
if (Array.isArray(destinations)) {
destinations.forEach((to) => {
edges.add({
from,
to,
label: symbol,
arrows: "to",
color: "#6b7280",
font: { size: 14 },
});
});
} else {
edges.add({
from,
to: destinations,
label: symbol,
arrows: "to",
color: "#6b7280",
font: { size: 14 },
});
}
});
});
}
const container = document.getElementById(containerId);
container.innerHTML = "";
return new vis.Network(container, { nodes, edges }, visOptions);
}
function generateNFAToDFASteps(nfa) {
const steps = [];
const explanations = [];
const outputStates = [];
// Step 1: Initialize
steps.push("Step 1: Initialize DFA construction");
explanations.push(
"We start by creating the DFA from the NFA using subset construction algorithm. Each DFA state will represent a set of NFA states."
);
outputStates.push({
states: [],
transitions: {},
startState: "",
finalStates: [],
});
// Step 2: Start state
const startState = `{${nfa.startState}}`;
steps.push(`Step 2: Create initial DFA state = ${startState}`);
explanations.push(
`The initial DFA state is the epsilon closure of the NFA start state '${nfa.startState}'.`
);
outputStates.push({
states: [startState],
transitions: {},
startState: startState,
finalStates: nfa.finalStates.includes(nfa.startState) ? [startState] : [],
});
// Step 3: Process transitions
const dfaStates = [startState];
const dfaTransitions = {};
const dfaFinalStates = nfa.finalStates.includes(nfa.startState)
? [startState]
: [];
// Simulate subset construction for first few steps
let stateCounter = 0;
nfa.alphabet.forEach((symbol, index) => {
if (
nfa.transitions[nfa.startState] &&
nfa.transitions[nfa.startState][symbol]
) {
const destinations = nfa.transitions[nfa.startState][symbol];
const newState = `{${destinations.join(",")}}`;
if (!dfaStates.includes(newState)) {
dfaStates.push(newState);
if (destinations.some((s) => nfa.finalStates.includes(s))) {
dfaFinalStates.push(newState);
}
}
if (!dfaTransitions[startState]) dfaTransitions[startState] = {};
dfaTransitions[startState][symbol] = [newState];
steps.push(
`Step ${3 + index}: Process symbol '${symbol}' from ${startState}`
);
explanations.push(
`From ${startState} on input '${symbol}', we reach ${newState}. Add this transition to DFA.`
);
outputStates.push({
states: [...dfaStates],
transitions: JSON.parse(JSON.stringify(dfaTransitions)),
startState: startState,
finalStates: [...dfaFinalStates],
});
}
});
// Final step
steps.push("Step " + (steps.length + 1) + ": DFA construction complete");
explanations.push(
"The resulting DFA is equivalent to the original NFA and accepts the same language."
);
outputStates.push({
states: [...dfaStates],
transitions: JSON.parse(JSON.stringify(dfaTransitions)),
startState: startState,
finalStates: [...dfaFinalStates],
});
return { steps, explanations, outputStates };
}
function generateDFAToNFASteps(dfa) {
const steps = [];
const explanations = [];
const outputStates = [];
steps.push("Step 1: Initialize NFA from DFA");
explanations.push(
"Converting DFA to NFA is straightforward since every DFA is already an NFA. We just need to ensure the transition function format is correct."
);
outputStates.push({
states: [],
transitions: {},
startState: "",
finalStates: [],
});
steps.push("Step 2: Copy states and start/final states");
explanations.push(
"All DFA states become NFA states with the same names and properties."
);
outputStates.push({
states: [...dfa.states],
transitions: {},
startState: dfa.startState,
finalStates: [...dfa.finalStates],
});
steps.push("Step 3: Convert transitions to NFA format");
explanations.push(
"Each DFA transition δ(q,a) = p becomes an NFA transition δ(q,a) = {p}. Single destinations become singleton sets."
);
// Convert transitions
const nfaTransitions = {};
Object.entries(dfa.transitions).forEach(([state, trans]) => {
nfaTransitions[state] = {};
Object.entries(trans).forEach(([symbol, destination]) => {
nfaTransitions[state][symbol] = Array.isArray(destination)
? destination
: [destination];
});
});
outputStates.push({
states: [...dfa.states],
transitions: nfaTransitions,
startState: dfa.startState,
finalStates: [...dfa.finalStates],
});
steps.push("Step 4: NFA conversion complete");
explanations.push(
"The resulting NFA is equivalent to the original DFA. No additional nondeterminism was introduced."
);
outputStates.push({
states: [...dfa.states],
transitions: nfaTransitions,
startState: dfa.startState,
finalStates: [...dfa.finalStates],
});
return { steps, explanations, outputStates };
}
function generateREToNFASteps(regex) {
const steps = [];
const explanations = [];
const outputStates = [];
steps.push("Step 1: Parse regular expression");
explanations.push(
`Parsing the regular expression: ${regex}. We'll use Thompson's construction algorithm.`
);
outputStates.push({
states: [],
transitions: {},
startState: "",
finalStates: [],
});
steps.push("Step 2: Create basic NFA for symbols");
explanations.push(
"Create basic NFAs for each symbol in the alphabet. Each symbol gets a simple two-state NFA."
);
outputStates.push({
states: ["q0", "q1"],
transitions: {},
startState: "q0",
finalStates: [],
});
steps.push("Step 3: Apply Thompson's construction");
explanations.push(
"Build NFA by combining basic NFAs according to regex operators (union, concatenation, Kleene star)."
);
outputStates.push({
states: ["q0", "q1", "q2"],
transitions: { q0: { ε: ["q1"] }, q1: {} },
startState: "q0",
finalStates: ["q2"],
});
steps.push("Step 4: NFA construction complete");
explanations.push(
`The resulting NFA accepts exactly the language defined by the regular expression ${regex}.`
);
outputStates.push({
states: ["q0", "q1", "q2", "q3"],
transitions: {
q0: { ε: ["q1"] },
q1: { a: ["q2"] },
q2: { ε: ["q3"] },
q3: {},
},
startState: "q0",
finalStates: ["q3"],
});
return { steps, explanations, outputStates };
}
function generateConversionSteps(conversionType, example) {
switch (conversionType) {
case "nfa-dfa":
return generateNFAToDFASteps(example);
case "dfa-nfa":
return generateDFAToNFASteps(example);
case "re-nfa":
return generateREToNFASteps(example.regex);
case "re-dfa":
const nfaResult = generateREToNFASteps(example.regex);
const dfaResult = generateNFAToDFASteps({});
return {
steps: [
...nfaResult.steps,
"--- Converting NFA to DFA ---",
...dfaResult.steps,
],
explanations: [
...nfaResult.explanations,
"Now we convert the intermediate NFA to DFA.",
...dfaResult.explanations,
],
outputStates: [...nfaResult.outputStates, ...dfaResult.outputStates],
};
case "nfa-re":
return {
steps: [
"Step 1: State elimination method initialization",
"Step 2: Add new start and final states",
"Step 3: Eliminate intermediate states",
"Step 4: Update transition labels with REs",
"Step 5: Final regular expression obtained",
],
explanations: [
"We use the state elimination method to convert NFA to regular expression.",
"Add new start state with ε-transition to old start, and new final state from old finals.",
"Systematically eliminate intermediate states, updating transition labels.",
"When eliminating a state, combine incoming and outgoing transitions with concatenation and union.",
"Continue until only start and final states remain, connected by the final regular expression.",
],
outputStates: [
{ states: [], transitions: {}, startState: "", finalStates: [] },
{
states: ["new_start", ...example.states, "new_final"],
transitions: {},
startState: "new_start",
finalStates: ["new_final"],
},
{
states: ["new_start", "new_final"],
transitions: {},
startState: "new_start",
finalStates: ["new_final"],
},
{
states: ["new_start", "new_final"],
transitions: {},
startState: "new_start",
finalStates: ["new_final"],
},
{
states: ["new_start", "new_final"],
transitions: {},
startState: "new_start",
finalStates: ["new_final"],
},
],
};
case "dfa-re":
return {
steps: [
"Step 1: Apply state elimination to DFA",
"Step 2: Create transition equations",
"Step 3: Solve for regular expressions",
"Step 4: Eliminate intermediate states",
"Step 5: Obtain final regular expression",
],
explanations: [
"Use state elimination method directly on the DFA.",
"Set up equations for each state in terms of regular expressions.",
"Solve the system of equations using substitution and Arden's theorem.",
"Systematically eliminate states while preserving language equivalence.",
"The final expression describes exactly the language accepted by the DFA.",
],
outputStates: [
{ states: [], transitions: {}, startState: "", finalStates: [] },
{
states: [...example.states],
transitions: example.transitions,
startState: example.startState,
finalStates: example.finalStates,
},
{
states: [...example.states],
transitions: example.transitions,
startState: example.startState,
finalStates: example.finalStates,
},
{
states: [...example.states],
transitions: example.transitions,
startState: example.startState,
finalStates: example.finalStates,
},
{
states: [...example.states],
transitions: example.transitions,
startState: example.startState,
finalStates: example.finalStates,
},
],
};
case "cfg-pda":
return {
steps: [
"Step 1: Analyze CFG structure",
"Step 2: Design PDA with three states",
"Step 3: Create transitions for pushing productions",
"Step 4: Add transitions for matching terminals",
"Step 5: Add transitions for non-terminals",
"Step 6: PDA construction complete",
],
explanations: [
"Analyze the context-free grammar to understand its structure and language.",
"Design PDA with start state, main state, and accept state.",
"Add transitions that push production rules onto the stack.",
"Add transitions that consume input symbols and match them with stack contents.",
"Add transitions that handle non-terminal symbols in derivations.",
"The resulting PDA accepts the same language as the original CFG.",
],
outputStates: [
{ states: [], transitions: {}, startState: "", finalStates: [] },
{
states: ["q0", "q1", "q2"],
transitions: {},
startState: "q0",
finalStates: ["q2"],
},
{
states: ["q0", "q1", "q2"],
transitions: { q0: { "ε,ε→S$": ["q1"] } },
startState: "q0",
finalStates: ["q2"],
},
{
states: ["q0", "q1", "q2"],
transitions: {
q0: { "ε,ε→S$": ["q1"] },
q1: { "a,a→ε": ["q1"], "b,b→ε": ["q1"] },
},
startState: "q0",
finalStates: ["q2"],
},
{
states: ["q0", "q1", "q2"],
transitions: {
q0: { "ε,ε→S$": ["q1"] },
q1: {
"a,a→ε": ["q1"],
"b,b→ε": ["q1"],
"ε,S→aSb": ["q1"],
"ε,S→ε": ["q1"],
},
},
startState: "q0",
finalStates: ["q2"],
},
{
states: ["q0", "q1", "q2"],
transitions: {
q0: { "ε,ε→S$": ["q1"] },
q1: {
"a,a→ε": ["q1"],
"b,b→ε": ["q1"],
"ε,S→aSb": ["q1"],
"ε,S→ε": ["q1"],
"ε,$→ε": ["q2"],
},
},
startState: "q0",
finalStates: ["q2"],
},
],
};
default:
return {
steps: ["Conversion not implemented"],
explanations: ["This conversion type is not yet implemented."],
outputStates: [
{ states: [], transitions: {}, startState: "", finalStates: [] },
],
};
}
}
function updateTitles(conversionType) {
const titles = {
"nfa-dfa": { input: "Input NFA", output: "Output DFA" },
"dfa-nfa": { input: "Input DFA", output: "Output NFA" },
"re-dfa": { input: "Regular Expression", output: "Output DFA" },
"re-nfa": { input: "Regular Expression", output: "Output NFA" },
"nfa-re": { input: "Input NFA", output: "Regular Expression" },
"dfa-re": { input: "Input DFA", output: "Regular Expression" },
"cfg-pda": { input: "Context-Free Grammar", output: "Pushdown Automaton" },
};
document.getElementById("input-title").textContent =
titles[conversionType].input;
document.getElementById("output-title").textContent =
titles[conversionType].output;
}
function beginConversion() {
const convType = document.getElementById("conversion-type").value;
const exampleKey = document.getElementById("example-picker").value;
const example = examples[convType][exampleKey];
if (!example) return;
currentExample = example;
currentConversionType = convType;
updateTitles(convType);
// Draw input graph
if (convType.startsWith("re-")) {
document.getElementById(
"box-input"
).innerHTML = `<div class="flex items-center justify-center h-full">
<div class="text-center">
<div class="text-2xl font-mono mb-2">${
example.regex || "Regular Expression"
}</div>
<div class="text-gray-600">${example.description}</div>
</div>
</div>`;
} else if (convType === "cfg-pda") {
document.getElementById(
"box-input"
).innerHTML = `<div class="flex items-center justify-center h-full">
<div class="text-center">
<div class="text-lg font-mono mb-2">Productions:</div>
<div class="text-sm">${
example.productions
? example.productions.join("<br>")
: "CFG Productions"
}</div>
<div class="text-gray-600 mt-2">${example.description}</div>
</div>
</div>`;
} else {
inputGraph = drawGraph("box-input", example);
}
// Clear output initially
document.getElementById("box-output").innerHTML =
'<div class="flex items-center justify-center h-full text-gray-500">Output will appear here as you progress through steps</div>';
// Generate conversion steps
const result = generateConversionSteps(convType, example);
currentSteps = result.steps;
currentExplanations = result.explanations;
outputStates = result.outputStates;
stepIndex = 0;
// Reset displays
document.getElementById("log-box").textContent =
"Ready to begin conversion. Click 'Next Step' to start.";
document.getElementById(
"explanation-box"
).innerHTML = `<strong>Example:</strong> ${example.description}<br><br>Click 'Next Step' to begin the conversion process.`;
// Reset button states
document.getElementById("btnPrev").disabled = true;
document.getElementById("btnNext").disabled = false;
}
function nextStep() {
if (stepIndex < currentSteps.length) {
const logBox = document.getElementById("log-box");
const explanationBox = document.getElementById("explanation-box");
if (stepIndex === 0) {
logBox.textContent = currentSteps[stepIndex];
} else {
logBox.textContent += "\n" + currentSteps[stepIndex];
}
explanationBox.innerHTML = `<strong>Step ${stepIndex + 1}:</strong><br>${
currentExplanations[stepIndex]
}`;
// Update output graph if we have output states for this step
if (outputStates && outputStates[stepIndex]) {
const outputState = outputStates[stepIndex];
if (outputState.states && outputState.states.length > 0) {
outputGraph = drawGraph("box-output", outputState, true);
} else if (currentConversionType.endsWith("-re")) {
// For conversions to regular expressions, show text output
document.getElementById(
"box-output"
).innerHTML = `<div class="flex items-center justify-center h-full">
<div class="text-center">
<div class="text-lg font-mono mb-2">Regular Expression:</div>
<div class="text-xl font-bold">(Under Construction)</div>
<div class="text-gray-600 mt-2">Step ${
stepIndex + 1
} of conversion</div>
</div>
</div>`;
}
}
stepIndex++;
// Update button states
document.getElementById("btnPrev").disabled = stepIndex === 1;
document.getElementById("btnNext").disabled =
stepIndex >= currentSteps.length;
if (stepIndex >= currentSteps.length) {
explanationBox.innerHTML +=
"<br><br><strong>Conversion Complete!</strong> The transformation has been successfully completed.";
}
}
}
function prevStep() {
if (stepIndex > 0) {
stepIndex--;
const logBox = document.getElementById("log-box");
const explanationBox = document.getElementById("explanation-box");
// Rebuild log up to current step
if (stepIndex === 0) {
logBox.textContent =
"Ready to begin conversion. Click 'Next Step' to start.";
explanationBox.innerHTML = `<strong>Example:</strong> ${currentExample.description}<br><br>Click 'Next Step' to begin the conversion process.`;
document.getElementById("box-output").innerHTML =
'<div class="flex items-center justify-center h-full text-gray-500">Output will appear here as you progress through steps</div>';
} else {
logBox.textContent = currentSteps.slice(0, stepIndex).join("\n");
explanationBox.innerHTML = `<strong>Step ${stepIndex}:</strong><br>${
currentExplanations[stepIndex - 1]
}`;
// Update output graph for previous step
if (outputStates && outputStates[stepIndex - 1]) {
const outputState = outputStates[stepIndex - 1];
if (outputState.states && outputState.states.length > 0) {
outputGraph = drawGraph("box-output", outputState, true);
}
}
}
// Update button states
document.getElementById("btnPrev").disabled = stepIndex === 0;