2009-08-08 11 views
1

私は次のコードを持っています。私は、式ツリーを構築し、私はあなたがC#3.0の独自の式ツリーへの単純な基本イントロについて私自身の式ツリーを解析する助け、C#

私のコード内
public enum OpertaionType { add, sub, div, mul} 

public class Node { 
    public Node(Node lhs, Node rhs, OpertaionType opType, int index) { 
     this.lhs = lhs; 
     this.rhs = rhs; 
     this.opType = opType; 
     this.index = index; 
    } 
    Node lhs; 
    Node rhs; 
    OpertaionType opType; 
    int index; 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // I don't want this to be part of the node data structure 
     // because in the actual implementation I will end up referencing an 
     // array of data 

     int[] value = new int[5]; 

     Node[] nodes = new Node[value.Length]; 
     for (int i = 0; i < value.Length; i++) 
     { 
      value[i] = i+1; 
      nodes[i] = new Node(null, null, 0, i); 
     } 



     // suppose I constructed the tree like that 
     // note that the end nodes are marked by non-negative index that indexes the 
     // values array 

     Node a = new Node(nodes[0], nodes[1], OpertaionType.add, -1); 
     Node b = new Node(nodes[2], a, OpertaionType.mul, -1); 
     Node c = new Node(b, nodes[3], OpertaionType.div, -1); 

     // How can I find the result of Node c programatically 
     // such that the result is (a[2]*(a[0]+a[1]))/a[3] = 9/4 

    } 
} 
+0

この宿題はありますか? –

+0

heyy hold on ..ここであなたの素晴らしい知識を共有することができます! – mustafabar

+0

いいえマーティンはいません – mustafabar

答えて

1

を詳細を見つけるだろう結果に

を見つけるためにそれを解析立ち往生しています、例えば参照しますhere;残念ながら、私はその主題に関する本当に幅広く深いテキストを知っていません。

独自の手書き形式の場合、再帰によって最も簡単に評価できます。擬似コードで:あなたは、入力値が整数である一方、分数の結果をしたいように見えるとして、さらにツイストとして

def valof(node): 
    if node.index >= 0: 
    return whateverarray[node.index] 
    L = valof(node.lhs) 
    R = valof(node.rhs) 
    if node.opType == add: 
    return L + R 
    if node.opType == mul: 
    return L * R 
    # etc etc 

、あなたの計算のために分数/有理数タイプを使用することを忘れない - C#は1が付属していますかどうかわかりません、最悪の場合、ネット上でたくさん見つけることができます;-)。

+0

アレックスありがとうございました。これは非常にうまくいきました – mustafabar

+0

組み込みの式ツリーはシリアライズ可能ではありません...私はWCFサービスを渡したいと思います:)これは妥当かどうかわかりません – mustafabar

3

あなたは値配列(コード未テスト)渡し、再帰的なアルゴリズムを必要とする:これは二重のすべての計算を実行すること

class Node{ 
    //... 
    double compute(int[] values){ 
    if(index >= 0) 
     return values[index]; // leaf node; value stored in array 
    switch(opType){ 
     case add: return lhs.compute(values)+rhs.compute(values); 
     case sub: return lhs.compute(values)-rhs.compute(values); 
     case div: return lhs.compute(values)*rhs.compute(values); 
     case mul: return lhs.compute(values)/rhs.compute(values); 
    } 
    throw new Exception("unsupported operation type"); 
    } 
} 

が気づくと、あなたが本当に9/4を望むなら、合理的なタイプを使う必要があります。

関連する問題