布尔逻辑/真值表和输出

时间:2013-02-17 19:42:30

标签: c# winforms

我目前正在尝试复制一种在C#中将真值表转换为布尔表达式的方法。我已经能够生成一个3变量(a,b,c)真值表并将其显示在多行文本框中。我创建了另外八个文本框供用户决定每个输入的输出:true(1)false(0)。但是在生成表格之后,我怎样才能显示具有true值的所有输出?

public partial class Form1 : Form
{
    public Form1() => InitializeComponent();

    string newLine = Environment.NewLine;
    bool a, b, c, d;

    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.AppendText(newLine + "A" + "\t" + "B" + "\t" + "C" + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = true; b = true; c = true;

        textBox1.AppendText(newLine + a + "\t" + b +  "\t" + c +newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = true; b = true; c = false;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = true; b = false; c = true;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = true; b = false; c = false;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = false; b = true; c = true;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = false; b = true; c = false;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = false; b = false; c = true;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);
        a = false; b = false; c = false;

        textBox1.AppendText(newLine + a + "\t" + b + "\t" + c + newLine);
        textBox1.AppendText("______________________________" + newLine);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Grab true value outputs and display in string
    }
}

enter image description here

enter image description here

上面的表是一个例子。我想以某种方式显示真实的输出值:

结果如下: 是的,是的 是的,假的 是的,真的 是的假的

3 个答案:

答案 0 :(得分:3)

尝试封装您的TruthItem(以及计算TruthValue的逻辑)。然后使用真值表(生成,迭代,计算等)很容易。

这是示例控制台应用。它没有你的文本框,但你会明白这一点。

public abstract class ThreeItemTruthRow
{
    protected ThreeItemTruthRow(bool a, bool b, bool c)
    {
        A = a; B = b; C = c;
    }

    public bool A { get; protected set; }
    public bool B { get; protected set; }
    public bool C { get; protected set; }

    public abstract bool GetTruthValue();
}

public class MyCustomThreeItemTruthRow : ThreeItemTruthRow
{
    public MyCustomThreeItemTruthRow(bool a, bool b, bool c)
        : base(a, b, c)
    {
    }

    public override bool GetTruthValue()
    {
        // My custom logic
        return (!A && B && C) || (A && !B && C) || (A && B && !C) || (A && B && C);
    }
}

class Program
{
    static void Main(string[] args)
    {
        var myTruthTable = GenerateTruthTable().ToList();
        //Print only true values
        foreach (var item in myTruthTable)
        {
            if (item.GetTruthValue())
                Console.WriteLine("{0}, {1}, {2}", item.A, item.B, item.C);
        }
        ////Print all values
        //foreach (var itemTruthRow in myTruthTable)
        //{
        //    Console.WriteLine("{0}, {1}, {2}", itemTruthRow.A, itemTruthRow.B, itemTruthRow.C);
        //}
        ////Print only false values
        //foreach (var item in myTruthTable)
        //{
        //    if (!item.GetTruthValue())
        //        Console.WriteLine("{0}, {1}, {2}", item.A, item.B, item.C);
        //}
        Console.ReadLine();
    }
    public static IEnumerable<MyCustomThreeItemTruthRow> GenerateTruthTable()
    {
        for (var a = 0; a < 2; a++)
            for (var b = 0; b < 2; b++)
                for (var c = 0; c < 2; c++)
                    yield return new MyCustomThreeItemTruthRow(
                        Convert.ToBoolean(a),
                        Convert.ToBoolean(b),
                        Convert.ToBoolean(c));
    }
}

编辑(包含WinForm的示例代码):
使用并引用上面的类(ThreeItemTruthRow和MyCustomThreeItemTruthRow)。

public partial class MainForm : Form

{
    public MainForm()
    {
        InitializeComponent();
    }

private void GenerateButton_Click(object sender, EventArgs e)
{
    OutputTextBox.Clear();
    OutputTextBox.Text += "A\tB\tC\r\n";
    OutputTextBox.Text += GetHorizontalLineText();

    var myTruthTable = GenerateTruthTable().ToList();
    foreach(var item in myTruthTable)
    {
        OutputTextBox.Text += GetFormattedItemText(item);
        OutputTextBox.Text += GetHorizontalLineText();
    }
}
private void ShowTrueValuesButton_Click(object sender, EventArgs e)
{
    OutputTextBox.Clear();
    OutputTextBox.Text += "True Values\r\n";
    OutputTextBox.Text += "A\tB\tC\r\n";
    OutputTextBox.Text += GetHorizontalLineText();

    var myTruthTable = GenerateTruthTable().ToList();
    foreach(var item in myTruthTable)
    {
        if(item.GetTruthValue())
            OutputTextBox.Text += GetFormattedItemText(item);
    }
}
private static string GetHorizontalLineText()
{
    return "-----------------------------------------------\r\n";
}
private static string GetFormattedItemText(MyCustomThreeItemTruthRow item)
{
    return string.Format("{0}\t{1}\t{2}\r\n", item.A, item.B, item.C);
}
private static IEnumerable<MyCustomThreeItemTruthRow> GenerateTruthTable()
{
    for (var a = 0; a < 2; a++)
        for (var b = 0; b < 2; b++)
            for (var c = 0; c < 2; c++)
                yield return new MyCustomThreeItemTruthRow(
                    Convert.ToBoolean(a),
                    Convert.ToBoolean(b),
                    Convert.ToBoolean(c));
    }
}

答案 1 :(得分:2)

创建将保存传感器输入并产生输出的类:

public class SensorInput
{
    public SensorInput(bool a, bool b, bool c)
    {
        A = a;
        B = b;
        C = c;
    }

    public bool A { get; private set; }
    public bool B { get; private set; }
    public bool C { get; private set; }
    public bool Output
    {
        // output logic goes here
        get { return A || B || C; }
    }
}

然后将输入列表绑定到DataGridView控件:

var inputs = new List<SensorInput>()
{
    new SensorInput(true, true, true),
    new SensorInput(true, true, false),
    new SensorInput(true, false, true),
    new SensorInput(true, false, false),
    new SensorInput(false, true, true),
    new SensorInput(false, true, false),
    new SensorInput(false, false, true),
    new SensorInput(false, false, false)
};

dataGridView1.DataSource = inputs;

默认情况下,布尔值将绑定到CheckBoxColumns。如果要将True / False作为文本,则手动添加四列。选择它们的类型(只读)TextBoxColumns,并提供绑定的属性名称。结果如下:

DataGridView

对于按输出等于 true 的过滤表,您可以使用Linq。像这样:

dataGridView1.DataSource = inputs.Where(i => i.Output);

答案 2 :(得分:1)

创建几个类来保存数据。

public class TruthTable {

    public TruthTable(int sensorCount) {
      if (sensorCount<1 || sensorCount >26) {
        throw new ArgumentOutOfRangeException("sensorCount");
      }
      this.Table=new Sensor[(int)Math.Pow(2,sensorCount)];
      for (var i=0; i < Math.Pow(2,sensorCount);i++) {
          this.Table[i]=new Sensor(sensorCount);
          for (var j = 0; j < sensorCount; j++) {
              this.Table[i].Inputs[sensorCount - (j + 1)] = ( i / (int)Math.Pow(2, j)) % 2 == 1;
          }
       }
    }   

    public Sensor[] Table {get; private set;}

    public string LiveOutputs {
      get {
        return string.Join("\n", Table.Where(x => x.Output).Select(x => x.InputsAsString));
      }
    }

    public string LiveOutPuts2 {
    get { 
        return string.Join(" + ", Table.Where(x => x.Output).Select (x => x.InputsAsString2));
    }
  }
}

// Define other methods and classes here
public class Sensor {

  public Sensor(int sensorCount) {
    if (sensorCount<1 || sensorCount >26) {
      throw new ArgumentOutOfRangeException("sensorCount");
    }
    this.SensorCount = sensorCount;
    this.Inputs=new bool[sensorCount];
  }

  private int SensorCount {get;set;}
  public bool[] Inputs { get; private set;}
  public bool Output {get;set;}

  public string InputsAsString {
    get {
        return string.Join(" ",Inputs.Select(x => x.ToString().ToUpper()));
    }
  }

  public string InputsAsString2 {
   get {
      var output=new StringBuilder();
      for (var i=0; i < this.SensorCount; i++) {
        var letter = (char)(i+65);
        output.AppendFormat("{0}{1}",Inputs[i] ? "" : "!", letter);
      }
      return output.ToString();
    }
  }
}

然后,您可以创建真值表的实例;

var table = new TruthTable(3);

然后将适当的输出设置为true

table.Table[3].Output=true;
table.Table[5].Output=true;
table.Table[6].Output=true;
table.Table[7].Output=true;

然后table.LiveOutputs会给你

FALSE TRUE TRUE
TRUE FALSE TRUE
TRUE TRUE FALSE
TRUE TRUE TRUE

table.LiveOutputs2将为您提供字符串

!ABC + A!BC + AB!C + ABC

我用过了!表示错误输入而不是上线

编辑---关于winforms的评论

自从我使用winforms代码以来已经有很长一段时间了,我通常都在使用WPF。

如果在代码级别添加控件,某些代码取决于表单的生成方式......

private CheckBox[] checkBoxes;
private TruthTable table;
private int sensors;

//Call this function from the constructor....
void InitForm() {
   this.sensors = 3;
   this.table= new TruthTable(this.sensors);
   this.checkBoxes = new CheckBox[this.sensors];
   for (Var i = 0; i < this.sensors; i++) {
     this.checkBox[i] = new CheckBox();
     // set the positioning of the checkbox - eg this.checkBox[i].Top = 100 + (i * 30);
     this.Controls.Add(this.checkBox[i]);

     // You can perform similar logic to create a text label control with the sensors in it.
   }
}


private void button1_Click(object sender, EventArgs e) {
   for (var i=0; i<this.sensors;i++) {
      this.table.Table[i].Output = this.checkBoxes[i].IsChecked;
   }
   this.outputTextBox.Text = this.table.LiveOutputs2;
}