资源简介
人工智能课程中合一算法的java实现,希望对大家有用
代码片段和文件信息
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Unify {
private static String EMPTY = “ “;
private static String FAIL = “Failed“;
private static List list1 = new ArrayList();
private static List list2 = new ArrayList();
public static void main(String[] args){
System.out.println(“请输入待判断的两个表达式,变量用小写字母表示,常量用大写字符或字符串表示。“);
Scanner input = new Scanner(System.in);
String E1 = input.nextLine();
list1 = Unify.getElements(E1);
String E2 = input.nextLine();
list2 = Unify.getElements(E2);
System.out.println(“最一般的表达式为:“ + Unify.unify(E1 E2));
}
private static List getElements(String E){
List list = new ArrayList();
for(int i = 0; i < E.length(); i++){
if(E.charAt(i) == ‘)‘)
list.add(“()“);
if((E.charAt(i) >= ‘a‘ && E.charAt(i) <= ‘z‘) || (E.charAt(i) >= ‘A‘ && E.charAt(i) <= ‘Z‘)){
int j = i+1;
while(j < E.length() && ((E.charAt(j) >= ‘a‘ && E.charAt(j) <= ‘z‘) || (E.charAt(j) >= ‘A‘ && E.charAt(j) <= ‘Z‘)))
j++;
list.add(E.substring(ij));
i = j - 1;
}
}
return list;
}
private static String unify(String E1 String E2){
if(E1.isEmpty() && E2.isEmpty())
return Unify.EMPTY;
if(Unify.isConstants(E1) && Unify.isConstants(E2)){
if(E1.equals(E2))
return Unify.EMPTY;
else
return Unify.FAIL;
}
if(Unify.isVariable(E1)){
if(!E2.equals(E1) && E2.contains(E1))
return Unify.FAIL;
else{
if(E2.equals(E1))
return Unify.EMPTY;
else
return E2 + “/“ + E1;
}
}
if(Unify.isVariable(E2)){
if(!E1.equals(E2) && E1.contains(E2))
return Unify.FAIL;
else{
if(E2.equals(E1))
return Unify.EMPTY;
else
return E1 + “/“ + E2;
}
}
if(E1.isEmpty() || E2.isEmpty())
return Unify.FAIL;
else{
String he1 = Unify.getFirstElement(list1);
E1 = Unify.getRest(E1 he1);
String he2 = Unify.getFirstElement(list2);
E2 = Unify.getRest(E2 he2);
String subs1 = Unify.unify(he1 he2);
if(subs1.equals(Unify.FAIL))
return Unify.FAIL;
String te1 = Unify.apply(subs1 E1 list1);
String te2 =
- 上一篇:随手指移动的自定义edittext
- 下一篇:Android计算器270793
评论
共有 条评论