-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFA.java
More file actions
88 lines (65 loc) · 3.09 KB
/
DFA.java
File metadata and controls
88 lines (65 loc) · 3.09 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
//Ikaia Melton
//Theoretical Foundation Project
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class DFA {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader(args[0]);// file for opening
BufferedReader br=new BufferedReader(fr);// BufferedReader applied on FileReader object
Scanner sc=new Scanner(System.in); // Scanner object for reading from console
String alphabet=br.readLine(); // reads alphabet from file
String states=br.readLine();// reads states from file
String startState=br.readLine();// reads start state from file
String acceptStates=br.readLine(); // reads accept states from file
/*Displays alphabet, states,start state and accept states*/
System.out.println("Alphabet: "+alphabet);
System.out.println("States: "+states);
System.out.println("Start state: "+startState);
System.out.println("Accept States: "+acceptStates);
String str="",s;
/*reads rules from file and concatenates them with a # symbol*/
while((s=br.readLine())!=null)
str=str+s+"#";
// System.out.println(str + " HERE");
String rules[]=str.split("#");/* splits the rules at # symbol to form an array of rules*/
System.out.println("Transition rules are:");// displays rules
for(String rule: rules) {
System.out.println(rule);
}
HashMap<String, List<String[]>> map = new HashMap<>();
// (Banana,0)->Banana
// (Banana,1)->Pudding
// (Pudding,0)->Banana
// (Pudding,1)->Pudding
for(String line: rules){
String start = line.substring(1, line.indexOf(","));
String finish = line.substring(line.indexOf(">")+1);
String number = line.substring(line.indexOf(",")+1, line.indexOf(",")+2);
map.putIfAbsent(start, new ArrayList<>());
map.get(start).add(new String[]{number, finish});
}
System.out.println("Enter the string for testing:");
String testString=sc.next();// reads a string from console for testing
String currentState = startState;
currentState = makeTransitions(map, testString, currentState);
if(acceptStates.contains(currentState)){
System.out.println("String accepted!");
} else{
System.out.println("String not accepted.");
}
}
private static String makeTransitions(HashMap<String, List<String[]>> map, String testString, String currentState) {
for(char state: testString.toCharArray()){
List<String[]> tempList = map.get(currentState);
for(String[] temp: tempList){
if(temp[0].equals(Character.toString(state))){
currentState = temp[1];
}
}
}
return currentState;
}
}