Last active
August 29, 2015 14:22
-
-
Save novohispano/63c5a19901b7d2e8472a to your computer and use it in GitHub Desktop.
Logic Gates Code Challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module And | |
class Double | |
attr_accessor :input_a, | |
:input_b | |
def initialize | |
@input_a = 0 | |
@input_b = 0 | |
end | |
def output | |
(input_a + input_b) == 2 ? 1 : 0 | |
end | |
end | |
class Triple | |
attr_accessor :input_a, | |
:input_b, | |
:input_c | |
def initialize | |
@input_a = 0 | |
@input_b = 0 | |
@input_c = 0 | |
end | |
def output | |
(input_a + input_b + input_c) == 3 ? 1 : 0 | |
end | |
end | |
class Multi | |
ALPHABET = ('a'..'z').to_a | |
ALPHABET.each do |chr| | |
define_method("input_#{chr}") do | |
instance_variable_get("@input_#{chr}") | |
end | |
define_method("input_#{chr}=") do |value| | |
instance_variable_set("@input_#{chr}", value) | |
end | |
end | |
attr_reader :inputs | |
def initialize(inputs) | |
@inputs = inputs | |
create_inputs | |
end | |
def create_inputs | |
ALPHABET.each do |chr| | |
instance_variable_set("@input_#{chr}", 0) | |
end | |
end | |
def output | |
inputs == sum ? 1 : 0 | |
end | |
private | |
def sum | |
ALPHABET.reduce(0) { |sum, char| sum += send("input_#{char}") } | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'minitest/autorun' | |
require 'minitest/pride' | |
require './logic_gates' | |
class LogicGatesTest < Minitest::Test | |
def test_double | |
gate = And::Double.new | |
gate.input_a = 1 | |
gate.input_b = 1 | |
assert_equal 1, gate.output | |
gate.input_b = 0 | |
assert_equal 0, gate.output | |
end | |
def test_triple | |
gate = And::Triple.new | |
gate.input_a = 1 | |
gate.input_b = 1 | |
assert_equal 0, gate.output # => 0 | |
gate.input_c = 1 | |
assert_equal 1, gate.output # => 1 | |
gate.input_a = 0 | |
assert_equal 0, gate.output # => 0 | |
end | |
def test_multi | |
gate = And::Multi.new(4) | |
gate.input_a = 1 | |
gate.input_b = 1 | |
gate.input_c = 1 | |
assert_equal 0, gate.output # => 0 | |
gate.input_d = 1 | |
assert_equal 1, gate.output # => 1 | |
gate.input_b = 0 | |
assert_equal 0, gate.output # => 0 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment