class Gate def initialize(type) @type = type.downcase.to_sym @inputs = [] @output = nil end def input= id raise "Neplatne hradlo (moc vstupu)" if (@type == :not && !@inputs.empty?) @inputs << id end def output= id raise "Neplatne hradlo (moc vystupu)" if @output @output = id end # má hradlo všechny potřebné vstupy? def has(inputs) raise "Neplatne hradlo (malo vstupu)" if @inputs.length < 1 raise "Neplatne hradlo (malo vystupu)" unless @output @inputs.each do |i| return false unless inputs.index(i) end end # vyhodnotí hradlo def result inputs vars = [] @inputs.each { |i| vars << inputs[i] } case @type when :not return vars[0] == 0 ? 1 : 0 when :xor x = 0 vars.each { |v| x += v } return x % 2 when :or vars.each { |v| return 1 if v == 1 } return 0 when :and vars.each { |v| return 0 if v == 0 } return 1 else raise "Neplatne hradlo (spatny typ)" end end attr_reader :type, :inputs, :output end