Class: LogicTools::NodeAnd

Inherits:
NodeNary show all
Defined in:
lib/logic_tools/logictree.rb

Overview

Represents an AND node

Instance Attribute Summary

Attributes inherited from NodeNary

#op

Instance Method Summary collapse

Methods inherited from NodeNary

#==, #distribute, #each, #flatten, #flatten_deep, #getVariablesRecurse, make, #reduce, #sort, #to_sym, #uniq

Methods inherited from Node

#distribute, #each, #each_line, #each_maxterm, #each_minterm, #eql?, #flatten, #flatten_deep, #getVariables, #hash, #inspect, #op, #simplify, #size, #to_std_conjunctive, #to_std_disjunctive, #to_sym

Constructor Details

#initialize(*children) ⇒ NodeAnd

Creates a new AND node with children.



586
587
588
# File 'lib/logic_tools/logictree.rb', line 586

def initialize(*children)
    super(:and,*children)
end

Instance Method Details

#dupObject

Duplicates the node.



591
592
593
# File 'lib/logic_tools/logictree.rb', line 591

def dup # :nodoc:
    return NodeAnd.new(@children.map(&:dup))
end

#evalObject

Computes the value of the node.



596
597
598
# File 'lib/logic_tools/logictree.rb', line 596

def eval()
    return !@children.any? {|child| child.eval() == false }
end

#to_sObject

Convert to a string.



635
636
637
638
639
640
641
642
643
644
645
646
647
648
# File 'lib/logic_tools/logictree.rb', line 635

def to_s # :nodoc:
    return @str if @str
    @str = ""
    # Convert the children to a string
    @children.each do |child|
        if (child.op == :or) then
            # Yes, need parenthesis
            @str << ( "(" + child.to_s + ")" )
        else
            @str << child.to_s
        end
    end
    return @str
end

#to_sum_product(flattened = false) ⇒ Object

Creates a sum fo product from the tree rooted by current node.

Argument +flattened+ tells if the tree is already flattend


603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/logic_tools/logictree.rb', line 603

def to_sum_product(flattened = false) # :nodoc:
    # Flatten if required
    node = flattened ? self : self.flatten_deep
    # print "node = #{node}\n"
    # Convert each child to sum of product
    nchildren = node.map {|child| child.to_sum_product(true) }
    # print "nchildren = #{nchildren}\n"
    # Distribute
    while(nchildren.size>1)
        dist = []
        nchildren.each_slice(2) do |left,right|
            # print "left=#{left}, right=#{right}\n"
            if right then
                dist << (left.op == :or ? left.distribute(:and,right) :
                                          right.distribute(:and,left))
            else
                dist << left
            end
        end
        # print "dist=#{dist}\n"
        nchildren = dist
    end
    # print "Distributed nchildren=#{nchildren}\n"
    # Generate the or
    if (nchildren.size > 1)
        return NodeOr.new(*nchildren)
    else
        return nchildren[0]
    end
end