C#: 0 & 1 Permutations

后端 未结 2 1564
粉色の甜心
粉色の甜心 2021-01-27 00:03

I want to list permutations with only 0 and 1. Similar to binary but allowing variable lengths, doesn\'t have to equal 8 length. For example:

0
1
00
01
10
11
000         


        
相关标签:
2条回答
  • 2021-01-27 00:05

    You can also use:

    using System;
    
    class Test
    {
        static void permute(int len)
        {
            for (int i=1; i<=len; i++) 
            {
                for (int j=0; j<Math.Pow(2, i); j++)
                {
                    Console.WriteLine (Convert.ToString(j, 2).PadLeft(i, '0'));
                }
            }
        }
    }
    

    Which involves no recursion :)

    0 讨论(0)
  • 2021-01-27 00:18

    I would do this as a recursive call, one function to do all of a specific length, another to call that for all relevant lengths. The following complete C# 2008 console application shows what I mean:

    using System;
    
    namespace ConsoleApplication1 {
        class Program {
            static void permuteN(string prefix, int len) {
                if (len == 0) {
                    System.Console.WriteLine(prefix);
                    return;
                }
                permuteN(prefix + "0", len - 1);
                permuteN(prefix + "1", len - 1);
            }
    
            static void permute(int len) {
                for (int i = 1; i <= len; i++)
                    permuteN("", i);
            }
    
            static void Main(string[] args) {
                permute(3);
            }
        }
    }
    

    This outputs:

    0
    1
    00
    01
    10
    11
    000
    001
    010
    011
    100
    101
    110
    111
    

    which is what I think you were after.

    0 讨论(0)
提交回复
热议问题