Program to eliminate unit productions from given CFG (context free grammar). - Java program
Write
a program to eliminate unit productions from given CFG.
Program:
package engineeringway;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class engineeringway {
/**
* @param args the
command line arguments
*/
public static void
main(String[] args) throws FileNotFoundException, IOException {
// TODO code
application logic here
BufferedReader
in = new BufferedReader(new FileReader("E://sid//input4.txt"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
int i=0;
int j=0;
int c=0;
for(i=0;i<stringArr.length;i++){
System.out.println(stringArr[i].length());
if(stringArr[i].length()==3){
c++;
}
}
StringBuilder[] pro1=new StringBuilder[c];
StringBuilder[] pro2=new StringBuilder[stringArr.length];
for(i=0;i<stringArr.length;i++){
pro2[i] = new StringBuilder("");
pro2[i].append(stringArr[i]);
System.out.println("-"+pro2[i]);
if(stringArr[i].length()==3){
pro1[j] = new StringBuilder("");
System.out.println(stringArr[i]);
pro1[j].append(stringArr[i]);
j++;
}
}
System.out.print("\n");
int count=0;
for(int b=0;b<pro1.length;b++)
{
String
b1;
b1=pro1[b].toString().trim();
String
c1=b1.substring(b1.length() - 1);
char ch = c1.charAt(0);
//System.out.println(ch);
if(ch>='A' &&ch<='Z'){
System.out.println(pro1[b]);
count++;
for(int q=0;q<pro2.length;q++){
char first=pro2[q].toString().charAt(0);
System.out.println(first);
if(ch==first){
//for(int r=0;r<pro2[q].length();r++)
//{
System.out.println(pro2[q].substring(2));
String
sub=pro2[q].substring(2);
for(int r=0;r<pro2.length;r++){
if(pro2[r].length()==3 &&
pro2[2].toString().charAt(0)==ch){
String
h=pro2[r].toString().replaceAll(String.valueOf(pro2[2].toString().charAt(0)),sub pro2[r].replace(0, pro2[r].length(), h
)} }
} }
}
}
for(int r=0;r<pro2.length;r++){
System.out.println(pro2[r]);
}
if(count==0){
System.out.println("Unit production doesn't
exist");
}
else{
System.out.println("Unit production exist");
}
}
}
Output:
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment