排列和路径组合?

时间:2018-05-29 10:23:06

标签: c# .net

我的输入类似于“dir1 / dir2 / Demo.txt”

组合我希望输出像

  • “DIR1 / DIR2 / Demo.txt”
  • “DIR1 / DIR2 / DEMO.txt”

  • “DIR1 / DIR2 / Demo.txt”

  • “DIR1 / DIR2 / DEMO.txt”

  • “DIR1 / DIR2 / Demo.txt”

  • “DIR1 / DIR2 / DEMO.txt”

  • “DIR1 / DIR2 / Demo.txt”

  • “DIR1 / DIR2 / DEMO.txt”

据我所知,我编写了如下代码

   var s = "dir1/dir2/Demo.txt";
   List<string> listPermutations = new List<string>();
   string[] array = s.Split('/');
   int iterations = (1 << array.Length) -1;
   for( int i = 0; i <= iterations; i++ )
   {
       for( int j = 0; j < array.Length; j++ )
            array[j] = (i & (1<<j)) != 0
                ? array[j].ToUpper()
                : array[j];
       listPermutations.Add(string.Join("/",array ));
   }

1 个答案:

答案 0 :(得分:1)

问题是,你一直在覆盖你的来源&#34;数组,使用临时数组代替每个单独的排列:

        var s = "dir1/dir2/Demo.txt";
        List<string> listPermutations = new List<string>();
        string[] array = s.Split('/');
        int iterations = (1 << array.Length) - 1;
        for (int i = 0; i <= iterations; i++)
        {
            var tmp = new string[array.Length];
            for (int j = 0; j < array.Length; j++)
                tmp [j] = (i & (1 << j)) != 0
                     ? array[j].ToUpper()
                     : array[j];
            listPermutations.Add(string.Join("/", tmp));
        }

输出(如果只是迭代listPermutations):

dir1/dir2/Demo.txt
DIR1/dir2/Demo.txt
dir1/DIR2/Demo.txt
DIR1/DIR2/Demo.txt
dir1/dir2/DEMO.TXT
DIR1/dir2/DEMO.TXT
dir1/DIR2/DEMO.TXT
DIR1/DIR2/DEMO.TXT

我尝试了一个&#34;最小修复&#34;对于您的给定代码,它具有以下结果:

  • 扩展名(.TXT)也将是大写的(因为如果仅由\拆分,它就是最后一个组件的一部分)。
  • 结果的顺序与您提议的顺序不同。
  • 生成的代码可能更有效/更清晰。

如果需要,你将不得不处理。