Class: TruthTable

Inherits:
Object
  • Object
show all
Defined in:
lib/truth-table.rb

Defined Under Namespace

Classes: Evaluator, InvalidVariableName

Constant Summary collapse

VERSION =
"0.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expression) ⇒ TruthTable

Returns a new instance of TruthTable.



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/truth-table.rb', line 38

def initialize(expression)
  @expression = expression
  @working_exp = expression.dup
  @working_exp.gsub!(' xor ', ' ^ ')
  @variables = ['(', ')', 'and', 'or', '&&' , '||', '!', 'not', '^'].inject(@working_exp) do |exp, op|
    exp.gsub(op, ' ')
  end.gsub(/\s+/, ' ').split(' ').uniq.reject { |v| ["true", "false"].include?(v) }
  @num_vars = @variables.length
  @variables.each do |v|
    raise InvalidVariableName unless v =~ /^[a-z_][a-zA-Z_0-9]*$/
  end
end

Instance Attribute Details

#expressionObject (readonly)

Returns the value of attribute expression.



35
36
37
# File 'lib/truth-table.rb', line 35

def expression
  @expression
end

#variablesObject (readonly)

Returns the value of attribute variables.



36
37
38
# File 'lib/truth-table.rb', line 36

def variables
  @variables
end

Class Method Details

.generate_true_false_arrays(num) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/truth-table.rb', line 51

def self.generate_true_false_arrays(num)
  true_falses = []
  val = 2 ** num
  (0...val).each do |i|
    k = val - 1 - i
    a = Array.new(num)
    for j in (0...num)
      a[j] = k[num - 1 - j] == 1
    end
    true_falses << a
  end
  true_falses
end

Instance Method Details

#evaluate(array) ⇒ Object



69
70
71
# File 'lib/truth-table.rb', line 69

def evaluate(array)
  Evaluator.new(@working_exp, Hash[@variables.zip(array)]).evaluate
end

#inspectObject



99
100
101
# File 'lib/truth-table.rb', line 99

def inspect
  "Number Variables: #{@num_vars}, Number Combinations: #{2 ** @num_vars}, Variables: #{@variables.inspect}, Expression: '#{@expression}'"
end

#num_combinationsObject



65
66
67
# File 'lib/truth-table.rb', line 65

def num_combinations
  2 ** @num_vars
end

#table_stringObject



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/truth-table.rb', line 73

def table_string
  lines = []

  temp = @variables.dup
  temp << @expression
  lines << " #{temp.join(" | ")} "

  lines << @variables.inject([]) do |a, v|
    a.concat(["-" * (v.length + 2)])
  end.concat(["-" * (@expression.length + 2)]).join("")

  self.class.generate_true_false_arrays(@num_vars).each do |array|
    vals = []
    (0...array.length).each do |i|
      len = @variables[i].length
      str = ' ' * len
      str[(len/2)] = (array[i] ? "T" : "F")
      vals << str
    end
    vals << "#{' ' * ((@expression.length / 2) - 1)}#{(evaluate(array) ? 'T' : 'F')}"
    lines << " #{vals.join(" | ")} "
  end

  lines.join("\n")
end