論理回路

http://arton.no-ip.info/diary/20080222.html#p01

久しぶりに論理回路を勉強した.

x y not_x not_y not_x and not_y not(not_x and not_y) (x or y)
T T F F F T T
T F F T F T T
F T T F F T T
F F T T T F F
require 'test/unit'
def _and(x, y)
 x and y
end

def _invert(x)
 not x
end

def _or(x, y)
# x or y
 _invert(_and(_invert(x),_invert(y)))
end

class TestOr < Test::Unit::TestCase
 def test_or
   assert_equal true, _or(true, true)
   assert_equal true, _or(true, false)
   assert_equal true, _or(false, true)
   assert_equal false, _or(false, false)
 end
end

ド・モルガンは、ごくごくたま〜にリファクタリングで使う.
not(not_x and not_y) <=> x or y

describe "ド・モルガンの法則" do
  before(:each) do
    p = [true, true, false, false]
    q = [true, false, true, false]
    @pq = p.zip(q)
  end

  it "not(p and q) == not p or not q" do
    @pq.each { |p, q|
      (not(p and q)).should == (not p or not q)
    }          
  end

  it "p and q == not(not p or not q)" do
    @pq.each { |p, q|
      (p and q).should == (not(not p or not q))
    }          
  end

  it "not(p or q) == not p and not q" do
    @pq.each { |p, q|
      (not(p or q)).should == (not p and not q)
    }          
  end
  
  it "p or q == not(not p and not q)" do
    @pq.each { |p, q|
      (p or q).should == (not(not p and not q))
    }
  end
end