2013-02-14 245 views
1

這是我的第一個問題,如果有任何錯誤,請糾正我的錯誤。 我有一套舊的規則在文件系統之一,我試圖將它們轉換成新的文件系統。 我有很多IF-ENDIFIF-ELSE-ENDIF嵌套在對方像下面一樣。需要一些將輸入轉換爲相應輸出的邏輯。 需要求助者的幫助。由於邏輯劃分IF-ELSE-ENDIF循環

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) 
+1

你是怎麼想出來的?在代碼中應用相同的邏輯... – yurib 2013-02-14 13:32:07

+0

我輸入那個手動輸出 – Noob 2013-02-14 13:34:45

+0

所以,你需要解析輸入並生成解析的輸出? – Henrik 2013-02-14 13:36:53

回答

0

我會假設你有一個可以在第一時間解析文件的邏輯。如果是這樣,那麼你就應該結束了抽象語法樹,其中每個節點看起來是這樣的:

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

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

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導致一個條件,打印出一個「!」在前面。

我希望有幫助!

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>")