Our boolean operators are AND
, OR
, XOR
, NAND
, NOR
, XNOR
and, in conjunction with one of those operators, NOT
.
Our numbers are \$1\$ and \$0\$.
The challenge is to write a program or function that calculates the results of the input.
Input
A string, array or other input format of your choice; containing alternating numbers and operators, e.g. 1 NOR 1
or ["1","OR","0","AND","1"]
or 0XOR0XNOR1
.
As an exception, NOT
must always come directly after another operator (e.g. 0 AND NOT 1
).. You can't implement NOT
by itself, and you won't ever get a chain of multiple NOTs (so 1 AND NOT NOT 0
is an invalid input).
The input must contain the strings for the operators (upper or lower-case is fine); no other representation can be used e.g. .+^¬||&&
etc.
Output
Return or print a single number (\$1\$ or \$0\$), derived using the calculation below. Invalid input can lead to any output you choose, or none.
Calculation
We're ignoring any precedence rules here - just calculate them in the order they come in (i.e. left-to-right) - as if someone was typing it into a calculator and pressing Enter after each number. NOT
is the only one that might cause some difficulties with that logic, as you need to figure out what it's NOT
-ing before you can apply the other operator.
Truth Tables
INPUT OUTPUT
A B AND NAND OR NOR XOR XNOR
0 0 0 1 0 1 0 1
0 1 0 1 1 0 1 0
1 0 0 1 1 0 1 0
1 1 1 0 1 0 0 1
IN OUT
A NOT A
0 1
1 0
Examples
1 NOR 1
=0
1 NOR NOT 0
=0
(equivalent to \$1\$ NOR \$1\$)1 NOR NOT 0 AND 1
=0
(equivalent to \$0\$ (from above) AND \$1\$)1 NOR NOT 0 AND 1 OR 1
=1
(equivalent to \$0\$ (from above) OR \$1\$)1 NOR NOT 0 AND 1 OR 1 XNOR 1
=1
(equivalent to \$1\$ (from above) XNOR \$1\$)1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0
=1
(equivalent to \$1\$ (from above) NAND \$1\$)1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0 XOR NOT 0
=0
(equivalent to \$1\$ (from above) XNOR NOT \$0\$ = \$1\$ XNOR \$1\$ = \$0\$)
Scoring
This is code-golf, but with a twist.
Your score is the number of bytes in your code, divided by the number of operators your code implements. Smallest score wins.
For example, if you only implement AND
, your score is the number of bytes of your code.
If you implement AND
, OR
, XOR
, NAND
, NOR
, XNOR
, NOT
(the full list of operators); then you get to divide the number of bytes by 7.
You must implement at least one operator, and you cannot implement NOT
by itself; as it must be preceded by another, different operator and so doesn't count as implemented otherwise.
Just because someone has a low score already, don't let that put you off trying to get the best score for your language! It would be interesting to compare across different numbers of implemented operators too - e.g. you might have a bad score for 2 operators, but you might be able to implement 7 really efficiently.
["1", "NOR", "NOT", "0"]
)? \$\endgroup\$True==1
andFalse==0
, but am never sure. \$\endgroup\$