笛卡尔积

时间:2015-02-09 02:32:31

标签: c# cartesian-product

我目前正在编写一个处理笛卡尔积的程序。我已经弄清楚输入两个数字的第一部分,并为输入的每个数字得到集合。但我需要的是两个数字的最终产品。 换句话说,我正在寻找我的产品看起来像这样:

{ (1,1), (1,2), (1,3), ... }

这是我现在的代码,我需要帮助的最后一部分。

private void btnCal_Click(object sender, EventArgs e)
{
    int iN, iM, i, j;
    string strOut1, strOut2, strOut;
    bool bN, bM;

    bN = int.TryParse(txtN.Text, out iN);
    bM = int.TryParse(txtM.Text, out iM);

    if (bN && bM && iM > 0 && iM > 0)
    {
        strOut1 = "{1";

        for (i = 2; i <= iM; i++)
            strOut1 += "," + i;
        txtFirst.Text = strOut1 + "}";

        strOut2 = "{1";

        for (j = 2; j <= iN; j++)
            strOut2 += "," + j;
        txtSecond.Text = strOut2 + "}";
    }

    //HERE IS WHERE THE PRODUCT CODE WILL BE AT

    if (bN && bM && iM > 0 && iM > 0)
    {
        for (i = 2; i <= iM; i++)
            for (j = 2; j <= iN; j++)

        strOut = ("strOut1");

        txtProduct.Text = strOut + " }";
    }
    else
        txtProduct.Text = "Please enter valid number.";
}

1 个答案:

答案 0 :(得分:1)

使用LINQ,一切皆有可能:

using System;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCal_Click(object sender, EventArgs e)
        {
            var tuples = from m in Enumerable.Range(1, int.Parse(txtM.Text))
                         from n in Enumerable.Range(1, int.Parse(txtN.Text))
                         select Tuple.Create(m, n);
            txtProduct.Text = "{" + String.Join(",", tuples) + "}";
        }
    }
}