开发者

How to generate a list of lists of digits?

I want to generat开发者_开发知识库e a list of lists like the one below. How would I do that in C#?

List<List<int>> data = {{0,0,0,0}, {0,0,0,1}, {0,0,0,2}, ..., {9,9,9,9}};


Try this.

var numbers = Enumerable.Range(0, 10);
var data = (from a in numbers
            from b in numbers
            from c in numbers
            from d in numbers
            select new List<int>() { a, b, c, d }).ToList();


Another option...

var data = Enumerable.Range(0, 10000)
                     .Select(x => new List<int>
                         { x / 1000, (x / 100) % 10, (x / 10) % 10, x % 10 })
                     .ToList();

And if you want to generate an arbitrary number of digits you can do something like this:

int n = 4;  // number of digits

var data = Enumerable.Range(0, (int)Math.Pow(10, n))
                     .Select(x =>
                         Enumerable.Range(1, n)
                                   .Select(y =>
                                       (x / (int)Math.Pow(10, n - y)) % 10)
                                   .ToList())
                     .ToList();


Since you know the size of the list in advance, I would prefer a native two dimensional array. The code would look like this:

        var data = new int[10000, 4];

        for (int i = 0; i < 10000; i++)
        {
            data[i,0] = (i / 1000);
            data[i,1] = (i / 100) % 10;
            data[i,2] = (i / 10) % 10;
            data[i,3] = i % 10;
        }


Simple and 'dumb' solution:

List<List<int>> data = new List<List<int>>();

int i;
int k;
int l;
int m;

for(i=0; i<10; i++){
    data.add(new List<int>);
    data[i].add(i);
    for(k=0; k<10; k++){
        data[i].add(k);
        for(l=0; l<10; k++){
        data[i].add(l);    
           for(m=0; m<10; k++){
           data[i].add(m);
           }
        }
    }
}

Not tested, but should do the biggest part of the job - if you want to fill up a list with all numbers from {0, 0, 0, 0} to {9, 9, 9, 9}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜