Created
April 29, 2015 21:04
-
-
Save takehiko/413891d24eddefafaa33 to your computer and use it in GitHub Desktop.
Associativity checker for well-known logical operations
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
#!/usr/bin/env ruby | |
# assocchecker.rb : associativity checker for well-known logical operations | |
# by takehikom | |
class AssociativityChecker | |
def initialize | |
end | |
def and(*param) | |
param.min | |
end | |
def or(*param) | |
param.max | |
end | |
def xor(*param) | |
param.inject {|result, item| result ^ item} | |
end | |
def nand(*param) | |
1 - param.min | |
end | |
def nor(*param) | |
1 - param.max | |
end | |
def start | |
[:and, :or, :xor, :nand, :nor].each do |op| | |
puts "[Truth table for #{op.to_s.upcase}]" | |
check(op) | |
puts | |
end | |
end | |
def check(sym = :xor) | |
flag_assoc = true | |
puts "x|y|z|A|B|C|D|E" | |
[0, 1].each do |x| | |
[0, 1].each do |y| | |
[0, 1].each do |z| | |
x_y = send(sym, x, y) | |
y_z = send(sym, y, z) | |
x_y__z = send(sym, x_y, z) | |
x__y_z = send(sym, x, y_z) | |
x_y_z = send(sym, x, y, z) | |
puts [x, y, z, x_y, y_z, x_y__z, x__y_z, x_y_z].join("|") | |
if x_y__z != x__y_z || x_y_z != x_y__z | |
flag_assoc = false | |
end | |
end | |
end | |
end | |
if $DEBUG | |
puts "A := x op y" | |
puts "B := y op z" | |
puts "C := A op z" | |
puts "D := x op B" | |
puts "E := x op y op z" | |
end | |
if flag_assoc | |
puts "This operation is associative." | |
else | |
puts "This operation is not associative." | |
end | |
end | |
end | |
if __FILE__ == $0 | |
AssociativityChecker.new.start | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment