I need help with the following question Here is my solution import java.io.*; im
ID: 3879087 • Letter: I
Question
I need help with the following question
Here is my solution
import java.io.*;
import java.lang.String;
public class Morganslaw {
public static void main(String[]args)
{
String c="(or a (and b (not ( or c d ))))";
String b="(and a (or b (not (and c (and d e))))))";// the given strings
String a=test(c);// method call to get sollution of given program and this method works any string you given
System.out.println(a+" ");
a=test(b);//method call to get sollution of given program
System.out.println(a);// printing updated string
}
public static String test(String d)// method defination to find solution of given problem
{
System.out.println("the given String is:");
System.out.println(d+" ");// print the given String
d = d.replace("(not ( or c d ))))", "(not c) (not d))))");
d=d.replace("(not (and c (and d e))))))", "(not c) (or (not d) (not e)))))");
String s1=d.toUpperCase(); // converting lower case to uppercase
System.out.println("the output/updated String is:");
return s1;//return updated string to main function
}
}
However, with my solution you have to manually manipulate each string using the replace method. I need a function that can take in any string and de morganfy it.
For example, if you have 20 strings I wouldn't want to use the replace method 20 times. I need the function to use demorgan law to find an equivalent expression
Please help thanks
Explanation / Answer
Ans : )
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Morganslaw {
public static void main(String[]args)
{
String c="(or a (and b (not ( or c d ))))";
String b="(and a (or b (not (and c (and d e))))))";// the given strings
System.out.println(test1(c));
System.out.println(test1(b));
}
public static String test1(String d)// method defination to find solution of given problem
{
String res="";
System.out.println("The given String is :"+d);
String temp[]=d.toLowerCase().split("\(not");
//
String tempR1[]=temp[1].trim().split(".\)");
String tempR[]=temp[1].trim().split("\)");
String endStr="";
for(int i=1;i<tempR1.length;i++)
endStr=endStr+")";
String middleStr=" (";
if(temp.length==2){
String temp1[]=tempR[0].trim().split("\(");
for(int i=1;i<temp1.length;i++){
String localTemp[]=temp1[i].trim().split("\s+");
if(temp1.length>2){
if(localTemp.length==2)
{
middleStr=middleStr+" not "+localTemp[1];
//System.out.println(localTemp[1]);
}else if(localTemp.length==3){
String t1="";
if(localTemp[0].equalsIgnoreCase("and"))
t1="or";
middleStr=middleStr+"("+t1+" (not "+localTemp[1]+") (not "+localTemp[2]+"))";
}
}else{
String t1="";
if(localTemp[0].equalsIgnoreCase("and"))
t1="or";
middleStr=middleStr+"("+t1+" (not "+localTemp[1]+") (not "+localTemp[2]+"))";
}
}
}
res=temp[0]+middleStr+endStr;
return res.toUpperCase();
}
}
Explanation : try this code, it may help you.