逻辑分频IF-ELSE-ENDIF循环

时间:2013-02-14 13:27:09

标签: java algorithm logic

这是我的第一个问题,如果有任何问题,请纠正我。 我在其中一个文档系统中有一些旧规则,我试图将它们转换为新的文档系统。 我有很多IF-ENDIFIF-ELSE-ENDIF互相嵌套在一起,如下所示。需要一些逻辑,用于将下面的输入转换为相应的输出。 需要帮助algo。感谢

INPUT:  
IF (Cond 1)  
    IF(Cond 2)  
    ENDIF  
    IF(Cond3)  
    ELSE  
    ENDIF  
ELSE  
    IF(Cond4)  
    ELSE  
        IF(Cond5)  
        ELSE  
        ENDIF  
    ENDIF  
    IF(Cond6)  
    ENDIF  
ENDIF  

必需的输出:

    IF(Cond1) AND (Cond2)  
    IF(Cond1) AND (Cond3)  
    IF(Cond1) AND !(Cond3)  
    IF!(Cond1) AND (Cond4)  
    IF!(Cond1) AND !(Cond4)  AND (Cond5)  
    IF!(Cond1) AND !(Cond4) AND !(Cond5)  
    IF!(Cond1) AND (Cond6)  

2 个答案:

答案 0 :(得分:0)

假设您将输入读取并解析为树状数据结构,其中每个节点表示一个'if-else'语句,而子节点是嵌套的if-else语句,这里有一些粗略的伪代码可以给你一般想法:

process(tree,output)
  if tree == null
    write output to file
    return
  for each child in body of if
     process(child,output + "AND <condition of root node in tree>")
  for each child in body of else
     process(child,output + "AND !<condition of root node in tree>")

答案 1 :(得分:0)

我将假设您具有可以首先解析文件的逻辑。如果是这样,那么你应该得到一个抽象语法树,其中每个节点看起来像这样:

If
  |
  +--- Condition
  |
  +--- Positive statement
  |
  +--- Negative statement

Sequence
  |
  +--- Statement 1
  |
  +--- Statement 2
  |
  ...
  |
  +--- Statement n

Terminal

其中Terminal表示具体声明。它们隐含在原始输入文件中。例如,“IF(COND2)ENDIF”将表示如下:

If
  |
  +--- Cond2
  |
  +--- Terminal
  |
  +--- (null)

在您的情况下,您的实际树看起来像这样:

If
  |
  +--- Cond1
  |
  +--- Sequence
  |      |
  |      +--- If
  |      |      |
  |      |      +--- Cond2
  |      |      |
  |      |      +--- Terminal
  |      |      |
  |      |      +--- (null)
  |      |
  |      +--- If
  |             |
  |             +--- Cond3
  |             |
  |             +--- Terminal
  |             |
  |             +--- Terminal
  |
  +--- If
       ...

要生成输出,您只需递归地向下遍历树,沿途构建一堆条件,然后当您到达语句时,输出整个条件堆栈,并在它们之间使用AND。这是一些伪代码:

void treeWalk(root):
    treeWalk(root, []);

void treeWalk(root, conditions):
    case root of:
        If(cond, positive, negative):
            if (positive is not null):
                treeWalk(positive, conditions + cond)
            if (negative is not null):
                treeWalk(negative, conditions + !cond)
        Sequence(statements):
            for each statement in statements:
                treeWalk(statements, conditions)
        Terminal:
            print "IF "
            for each condition in conditions:
                if (condition is not the last condition):
                    print " AND "
                print condition

这里我使用+来表示将项目附加到列表中。假设!cond导致一个条件,用“!”打印出来。在前面。

我希望有所帮助!