Create truth table in C#

Asked

Viewed 1,665 times

1

I have a test function that should receive different input combinations, to define these patterns I will use a truth table.

However, I’m having difficulty generating the truth table, I made an initial prototype, which works well with up to 11 entries, from this it gets very slow.

I did it this way:

Using Random Gero binary numbers for each of the entries. For example: if the program has 5 entries, Gero 5 random numbers (between 0 and 1).

These numbers are joined in a string to form the combination and then played in a list (if unique or not already discovered). From the number of entries, I can know the total number of combinations to be generated, so by completing the total, the program ends.

However, by trying to figure out each combination randomly, by requiring a truth table with 20 entries, for example (which would generate over 1 million combinations), the program becomes extremely slow to complete the task. Because in the end, many combinations are repeated that have already been created and the discovery of new combinations becomes extremely difficult. There is another more efficient way to solve this problem?

public void GerarTabela(int entradas)
    {
        double TotalDeLinhas = Math.Pow(2,Convert.ToDouble(entradas)); // Calcula o total de linhas a serem geradas;
        int[] linha = new int[entradas]; // Cada elemento da linha é jogado em uma posição do vetor
        int LinhasGeradas = 0;
        string LinhaString = ""; // Do vetor, os elementos são unidos nesta String
        List<string> linhas = new List<string>();
        Random randNum = new Random();

        while (LinhasGeradas < TotalDeLinhas) //Permanece no loop enquanto não completar todas as combinações.
        {      
            for (int i=0; i < Entradas; i++) // Gera uma combinação
            {
                   linha[i] = new int();
                   linha[i] = randNum.Next(0, 2); //Gera um num. aleatório entre 0 e 1;
            }

            for (int i=0; i < Entradas; i++) //Transforma o vetor de combinações em uma única string. (Ex: 0 - 1 - 0 - 1)
            {
                if (i == Entradas - 1) // Se for o ultimo número da combinação, não irá ter traço após ele.
                {
                    LinhaString += linha[i];
                } else
                {
                    LinhaString += linha[i] + " - ";
                }
            }

            if (!linhas.Contains(LinhaString)) // Se não tiver esta combinação na lista, adiciona ela.
            {
                linhas.Add(LinhaString);                    
                LinhasGeradas++;
            }
            LinhaString = "";                                       
        }
        MessageBox.Show("Tabela verdade gerada com sucesso!","Concluído!");           
    }
}
  • 4

    Can you put the code C# in your question, please?

  • As requested, I included the code here.

  • 1

    This random path is very strange. Have some motivation to use it?

  • It was a gambit, because my logical knowledge is limited, but I’ve already removed.

1 answer

0


You can do the following:

True table combinations can be interpreted as a binary number in which each digit is a variable.

Example:

A | B
0   0 >> 0 binario
0   1 >> 1 binario
1   0 >> 2 binario
1   1 >> 3 binario

So.. Voce can generate the sequence of binary numbers and assign each digit to each variable Voce has.

To ensure that the number has 5 digits, Voce can convert the number to String using the String.Padleft(quantity_variables,"0")

And after having the binary number as String.. Voce assigns each digit of it to each variable of yours, so will have all combinations of the truth table.

Code example:

For i As Integer = 0 to (quantidade_variaveis - 1)
  string binario = Convert.ToString(i, 2)
  binario = binario.PadLeft(quantidade_variaveis,"0")
  char[] arr = binario.toCharArray(0, binario.length)
  //variavel 1 = arr[0]
  //variavel 2 = arr[1]
  ...

End For
  • This solved the gambit I had created, because now I no longer use Random. However, the speed to create larger tables, amazingly, is similar.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.