views:

116

answers:

2

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
001
010
011
100
101
110
111

All the way until the length of X is met. How can this be done?

+4  A: 

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.

paxdiablo
+3  A: 

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 :)

NullUserException
Ah, exactly how I imagined in my head but did not convey correctly. :)
Jeff M