package com.***.hsf;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String condition = "( ( A & B & C ) | D ) & E";
judge(condition);
}
// 测试用条件结果
public static Map<String,Boolean> data = new HashMap<String,Boolean>(){
private static final long serialVersionUID = 1L;
{
put("A",true);
put("B",true);
put("C",false);
put("D",true);
put("E",true);
}};
// 测试用执行条件
public static boolean excute(String element) throws IllegalArgumentException{
Boolean flag = data.get(element);
if(flag!=null){
return flag.booleanValue();
}
throw new IllegalArgumentException("条件未定义:"+element);
}
// 逻辑符号
public static final String lk = "(";
public static final String rk = ")";
public static final String and = "&";
public static final String or = "|";
public static final String no = "!";
/**
* 最小原子组
* @param condition
* @return
*/
public static boolean judge(String condition){
condition = replaceBlank(condition);
while(true){
System.out.println("从这里开始 :"+condition);
// 寻找第一个")", 然后在这个位置往前寻找第一个"(", 最后截取该区间
int rk_index = condition.indexOf(rk);
String condition_after = "";
String item = condition;
if(rk_index>-1){
String pre_condition = condition.substring(0, rk_index);
int lk_index = pre_condition.lastIndexOf(lk);
item = condition.substring(lk_index, rk_index+1); // (a&b&c)
boolean flag = judgeItem(item);
condition_after = condition.substring(0, lk_index) + String.valueOf(flag) + condition.substring(rk_index+1);
}else{
boolean flag = judgeItem(item);
condition_after = String.valueOf(flag);
}
System.out.println("item:"+item);
System.out.println("condition_after :"+condition_after);
condition = condition_after;
if(Boolean.TRUE.toString().equals(condition_after)){
return true;
}
if(Boolean.FALSE.toString().equals(condition_after)){
return true;
}
}
}
public static boolean judgeItem(String condition){
String c1 = condition.replace(lk, "");
String c2 = c1.replace(rk, "");
String[] elements = getElements(c2);
// 组织形态:a&b&c 或 a|b|c
boolean is_and_model = true;
if(condition.contains(or)){
is_and_model = false;
}
boolean result = true;
if(is_and_model){
for(String element : elements){
boolean flag = judgeElements(element);
if(!flag){
result = false;
break;
}
}
}else{
for(String element : elements){
boolean flag = judgeElements(element);
if(flag){
result = true;
break;
}else{
result = false;
}
}
}
return result;
}
/**
* 原子分割
* @param condition
*/
public static String[] getElements(String condition){
return condition.split("&|\\|");
}
public static boolean judgeElements(String element){
if(Boolean.TRUE.toString().equals(element)){
return true;
}else if(Boolean.FALSE.toString().equals(element)){
return false;
}else{
return excute(element);
}
}
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
}