C#: 0 & 1 Permutations

后端 未结 2 1594
粉色の甜心
粉色の甜心 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: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.

提交回复
热议问题