c++ - 使用 C/C++ 实现德摩根定律

标签 c++ c demorgans-law

  • 表达式 1:(A 和 B 或(非 C))

  • 表达式 2:not((not A) or (not B) and C)

我想将表达式 2 更改为表达式 1。所以表达式可以表示为一棵树,如下图所示。这意味着“非”操作只能存在于叶节点中。

enter image description here

变换基于De Morgan's Law .

这是我的问题:

有没有C/C++库实现这个功能?我对 C/C++ 库了解不多。我搜索了GMPhttp://mathworld.wolfram.com/但没有找到解决办法。

谢谢!

最佳答案

当你递归地思考它时,规则很简单:

  • 不是(X 和 Y) ==> (不是 X)或(不是 Y)
  • 不是(X 或 Y) ==> (不是 X)和(不是 Y)

所以在 C++ 中:

struct Node {
    virtual ~Node() {};
    virtual Node *copy() = 0;
    virtual Node *negation() = 0;

private:
    // Taboo
    Node(const Node&);
    Node& operator=(const Node&);
};

struct AndNode : Node {
    Node *left, *right;
    AndNode(Node *left, Node *right) : left(left), right(right) {}
    ~AndNode() { delete left; delete right; }
    Node *copy() { return new AndNode(left->copy(), right->copy()); }
    Node *negation();
};

struct OrNode : Node {
    Node *left, *right;
    OrNode(Node *left, Node *right) : left(left), right(right) {}
    ~OrNode() { delete left; delete right; }
    Node *copy() { return new OrNode(left->copy(), right->copy()); }
    Node *negation();
};

struct NotNode : Node {
    Node *x;
    NotNode(Node *x) : x(x) {}
    ~NotNode() { delete x; }
    Node *copy() { return new NotNode(x->copy()); }
    Node *negation();
};

struct VarNode : Node {
    std::string var;
    VarNode(const std::string& var) : var(var) {}
    Node *copy() { return new VarNode(var); }
};

andor 运算的否定代码简单地应用了德摩根定律,从而将否定“推”到了树上

Node *AndNode::negation() {
    return new OrNode(left->negation(), right->negation());
}

Node *OrNode::negation() {
    return new AndNode(left->negation(), right->negation());
}

否定的否定代替了省略简化

Node *NotNode::negation() {
    return x->copy();
}

只有叶节点实际上包含在否定操作中

Node *VarNode::negation() {
    return new NotNode(this->copy());
}

正如你所见,摩根定律只有两行,其他的都是如何在 C++ 中表示表达式树。拥有一个库来实现德摩根变换是没有意义的,因为一旦有了表示,它就绝对微不足道了。

一个能够使用不同树表示的包装器的实现将是 99% 的样板文件和接口(interface)代码来实现两行代码(完全是废话)。

只需使用您拥有的任何树表示形式直接实现即可。

关于c++ - 使用 C/C++ 实现德摩根定律,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20781970/

相关文章:

c++ - 如何将值放入数组的动态数组中并在 C++ 中删除它们

c++ - 运行 FUSE c++ 代码时的奇怪行为

c - 尝试使用 gcc 编译时出错

python - 在 python 中使用德摩根定律有什么好处吗?

boolean-expression - 用德摩根定律简化 bool 表达式

c++ - 我的逻辑有什么问题?

c - 在 C 中定义矩阵

c - 基本 C 循环比较

boolean-logic - bool 代数 - 证明德摩根定律

c++ - 使用重载的普通 new 运算符放置 new