Is the gate set universal?

A set of gates is functionally complete (universal) if every Boolean function can be built from it. NAND alone is, and so is NOR alone. AND with OR is not, because you cannot build NOT from them.

What to build

Decide whether a set of gates can build every function of two variables.

Requirements

  • The gate names are NOT (1 input) and AND, OR, NAND, NOR, XOR, XNOR (2 inputs).
  • Starting from the two inputs a and b, you may feed any gate with any signals you have made. No constants are given.
  • Print universal if all 16 two-variable functions can be made. Otherwise print not universal and how many of the 16 can be made, as in not universal 4.

Input

One line with the names of the gates in the set, separated by spaces.

Output

One line, as described.

Constraints

The set has 1 to 7 gates, all different.

Example

Input:

NAND

Output:

universal

Why it works

Every function of a and b is one of 16 truth tables, so the set of functions you can reach is a subset of 16 and the search ends. A universal set must reach all of them, because a universal set can build every function, in particular the 16 of two variables. For example, from NAND you get NOT a, then AND, then OR, and so on. From AND and OR you only ever reach the 4 monotone functions a, b, a AND b, a OR b.

Examples

Example 1 · Input
NAND
Expected output
universal
Example 2 · Input
AND OR
Expected output
not universal 4

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Represent a function of a and b by its 4-bit truth table, with rows 00, 01, 10, 11. The input a is 0b0011 and b is 0b0101.

Hint 2

Start with the set {a, b}. Repeatedly apply every gate to the functions you have (every pair for 2-input gates), and add the results, until nothing new appears.

Hint 3

A set of gates is universal exactly when all 16 truth tables appear. NOT is 15 - x (flip 4 bits); the other gates work bit by bit on the tables.

Solution

Show one correct solution (try it yourself first)
gates = input().split()
A, B = 0b0011, 0b0101
FULL = 0b1111
two = {"AND": lambda x, y: x & y, "OR": lambda x, y: x | y, "NAND": lambda x, y: FULL ^ (x & y),
       "NOR": lambda x, y: FULL ^ (x | y), "XOR": lambda x, y: x ^ y, "XNOR": lambda x, y: FULL ^ (x ^ y)}
reached = {A, B}
changed = True
while changed:
    changed = False
    for g in gates:
        found = set()
        if g == "NOT":
            found = {FULL ^ x for x in reached}
        else:
            found = {two[g](x, y) for x in reached for y in reached}
        if not found <= reached:
            reached |= found
            changed = True
print("universal" if len(reached) == 16 else "not universal " + str(len(reached)))

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: NAND and NOR: the universal gates →