Search code examples
c#recursiontruthtable

Truth table using recursion


i am trying to create a truth table in c# for 3 symbols so it should produce 2^3 = 8 tables. but my recursive method is not working.

My code is below. in each loop i add a symbol and make new dictionary with one true and one false value.

    public void TTEntails()
    {
        Queue<string> s = new Queue<string>();
        s.Enqueue("p");
        s.Enqueue("q");
        s.Enqueue("r");
        TTCheckAll(s, new Dictionary<string, bool>());
    }


    public void TTCheckAll(Queue<string> symbol, Dictionary<string, bool> model)
    {
        if (symbol.Count == 0)
        {
            PLTrue(model);
        }
        else
        {
            string topSymbol = symbol.Dequeue();
            TTCheckAll(symbol, ReturnDict(model, topSymbol, true));
            TTCheckAll(symbol, ReturnDict(model, topSymbol, false));
        }
    }

    private Dictionary<string, bool> ReturnDict(Dictionary<string, bool> model, string key, bool value)
    {
        Dictionary<string, bool> newDict = new Dictionary<string, bool>(model);
        newDict.Add(key, value);
        return newDict;
    }

the result produced is as follows:

p, True
q, True
r, True


p, True
q, True
r, False


p, True
q, False


p, False

the result should be

p, True
q, True
r, True

p, True
q, True
r, false

p, True
q, false
r, True

p, True
q, false
r, false

p, false
q, True
r, True

p, false
q, True
r, false

p, false
q, false
r, True

p, false
q, false
r, false

Solution

  • You need to pass a copy of a queue to each true/false branch:

    public void TTCheckAll(Queue<string> symbol, Dictionary<string, bool> model)
    {
        if (symbol.Count == 0)
        {
            PLTrue(model);
        }
        else
        {
            string topSymbol = symbol.Dequeue();
            TTCheckAll(new Queue<string>(symbol), ReturnDict(model, topSymbol, true));
            TTCheckAll(new Queue<string>(symbol), ReturnDict(model, topSymbol, false));
        }
    }