一道算法题——8选6全排列

在网上看到一道题目:给定一个字符串包含8组元素,任取其中六组进行全排列。

例如: string str = "01 02 03 04 05 06 07 08";   从中输出所有由其中六个组成的序列。

思路:是用2进制来表示这个字符串的所有排列情况, 对每一位为1则输出,如11111100则是010203040506;而最小的是00111111;

代码如下:

        //8选6的全排列
        public static void FullArrangement() {
            string str = "01 02 03 04 05 06 07 08";
            string[] nstr = str.Split(' ');

            int tar = 6;    //目标选择6个
            int m = (0x01<<6)- 1;   // 00111111;
            int n = m << 2;         // 11111100;
            
            for (int i = m; i <= n; i++) {
                int k = i;      //保存i;
                int temp = 1;   //用来比较k的每一位是否为1;
                int len = 0;  //记录每一次循环的i中有多少个1;
                int index = 0;
                while (index < 8) {
                    if ((k & temp) == temp) {      //对k的每一位判断是否为1
                        len++;
                    }
                    index++;
                    //Console.WriteLine(len);
                    temp <<= 1;                    //temp进位来匹配k的每一位
                    if (len > 6) break;
                }

                //如果相等则当前i 总共有6个1,则进行输出
                if (len == tar) {
                    int current = 1;    //对i的每一位进行判断是否为1
                    for (int j = 0; j < str.Length; j++) {
                        if ((i & current) == current) {
                            Console.Write(nstr[j] + " ");
                        }
                        current <<= 1;
                    }
                    Console.WriteLine();
                }
            }
        }

猜你喜欢

转载自blog.csdn.net/m0_37845126/article/details/82886714