简体   繁体   中英

can anyone help me to create ternary numbers of digits 0,1,2?

I want to create a list of number combinations which consists of only three digits (0, 1, 2) . If n=1 then the result is like this {0, 1, 2} .If n=2 then result is {00, 01,02, 10, 11, 12, 20, 21, 22} . If n=3 the result will be like {000,001 etc 222} . I have tried to create this function using recursion. but i failed to create.How can I use iterations to create such list.

Try converting to strings, checking the (length <= n), and prepending (n - length) 0's if necessary. [EDIT] That is, assuming you are talking about the formatting... [EDIT v2] I am sure this is not the fastest way to do it, but you could recursively list all numbers from 0 - x and use the aforementioned string methods to iterate over the numbers an check whether any characters other than 0 - n are used.

A recursive approach could work well here, If you are running out of memory you might be going about it the rong way or you might just have a bug.

If you want to do this by iteration you can look at the problem this way: you want all the numbers from 0 to 3^n - 1 in base 3. now you just need to convert to base 3 (and pad with 0s)

This code will give you an idea about how to approach these problems recursively. Because of the recursive nature it will have a quite a lot of duplicates. I leave that to you to remove those.Also it prints output for all n

public void GetMaxPerm(int[] array, int k, List<int> output, int start, int end)
    {
        string str = GetString(output);
        Console.WriteLine(str);
        if (k == end)
        {

            return;
        }
        for (int i = start; i < end; i++)
        {
            output.Add(array[i]);
            GetMaxPerm(array, k + 1, output, start , end);
            output.Remove(array[i]);
            GetMaxPerm(array, k + 1, output, start, end);
        }

        return;

    }

    private string GetString(List<int> output)
    {
        string opString = String.Empty;
        foreach (var str in output)
        {
            opString = opString + String.Format(" {0} ", str);
        }
            return opString;
    }

Test Code :

 [TestMethod()]
    public void GetMaxTest1()
    {
        int[] array = new[] { 0, 1, 2 };
        Class obj = new Class();
        List<int> output = new List<int>();
        obj.GetMaxPerm(array, 0, output, 0, 3);
    }

Check this Gist

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM