# Generate truth table for n operators

I've been tasked with writing a function that generates a table given n operators. The truth table must be in a list and each row of the table must be in separate lists (inside the main list).

I know the solution involves recursion but I just can't seem to think it through.

Can someone help me out? This is only a small part of the assignment.

## Answers

Easiest way I can think of off the top of my head is to simply convert 2^n to binary and count down, then convert the output to a list.

ie for n=3:

Truth table:

a b c 0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1

2^3 = 8, 8 in binary = 1000, start from 1000-1 = 111 and work your way down to 0, record outputs, and voila!

If hkf's interpretation of your question is right, this should work in Racket:

#lang racket (define (generate-table n) (if (zero? n) '(()) (for*/list ((y (in-list (generate-table (sub1 n)))) (x (in-list '(0 1)))) (cons x y))))

Use it like this:

(generate-table 3) > ((0 0 0) (1 0 0) (0 1 0) (1 1 0) (0 0 1) (1 0 1) (0 1 1) (1 1 1))

Let's assume that all N operators are binary functions, like AND and OR.

;; Common Lisp (defun truth-tables (ops) (loop for op in ops collecting (loop for args in '((nil nil) (nil t) (t nil) (t t)) collecting (eval `(,op ,@args))))) (truth-tables '(and or xor)) -> ((NIL NIL NIL T) (NIL T T T) (NIL T T NIL))

This gives you an idea. Well, here I don't have "each row of the truth table" as a sublist; I have the columns for the AND, OR and XOR truth tables, respectively. The input variable combinations are left implicit: you know that the third entry of every one corresponds to (<op> t nil). Your description of the problem is not very clear.

As you can also see, I cheated by using the Lisp operators through generated code which is dynamically evaluated.