C#以排列组合中的“组合”方式遍历某个文件夹下的所有文件

参考自:http://blog.csdn.net/zmazon/article/details/8315418#comments

 private void button1_Click(object sender, EventArgs e)
        {
            //temp文件夹下存放着我们的环境因子
            DirectoryInfo folder = new DirectoryInfo(@"E:\work\test\data\temp");
            string fileName;
            FileInfo[] file = folder.GetFiles("*.asc");//只读取asc文件
            string[] AttributeFiles = new string[file.Length];
            for (int i = 0; i < file.Length; i++)
            {
                fileName = folder + "\\" + file[i].ToString();
                AttributeFiles[i] = fileName;  
            }

            int r = 3;//组合数,即C(r,n)中的r
            if (null == AttributeFiles || AttributeFiles.Length == 0 || r <= 0 || r > AttributeFiles.Length)
            {
                MessageBox.Show("请检查文件夹的文件是否为空,参数n的设置是否有误。");
            }
            string[] AttributeFilesResult = new string[r];
            getCombination(AttributeFiles, r, 0, AttributeFilesResult, 0);
        }

        private void getCombination(string[] a, int r, int begin, string[] b, int index)
        {
            string AttributeFile = "";
            if (r == 0)
            {
                for (int i = 0; i < index; i++)
                {
                    AttributeFile = AttributeFile + b[i] + " ";

                }
                Console.WriteLine("AttributeFile=" + AttributeFile);

            }
            for (int i = begin; i < a.Length; i++)
            {
                for (int j = 0; j < r; j++)
                {
                    if (j % r != 0)

                    {  
                        b[index] = a[i] + "#";//遍历文件,生成路径+文件名,在每个路径文件名后面加“#”号,末尾元素不加
                    }
                    else
                    {
                        b[index] = a[i];
                    }
                }

                getCombination(a, r-1,i+1,b,index+1);
            }

        }

程序部分输出结果如下(C(3,4),从文件夹中的4个文件中选出r=3的组合):

AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\slope.asc 
AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\twi.asc 
AttributeFile=E:\work\test\data\temp\horizc.asc# E:\work\test\data\temp\slope.asc# E:\work\test\data\temp\twi.asc 
AttributeFile=E:\work\test\data\temp\profc.asc# E:\work\test\data\temp\slope.asc# E:\work\test\data\temp\twi.asc 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值