Performance issue with generation of random unique numbers

前端 未结 10 532
星月不相逢
星月不相逢 2021-01-17 13:47

I have a situation where by I need to create tens of thousands of unique numbers. However these numbers must be 9 digits and cannot contain any 0\'s. My current approach is

10条回答
  •  鱼传尺愫
    2021-01-17 14:22

    The trick here is that you only need ten thousand unique numbers. Theoretically you could have almost 9,0E+08 possibilities, but why care if you need so many less?

    Once you realize that you can cut down on the combinations that much then creating enough unique numbers is easy:

    long[] numbers = { 1, 3, 5, 7 }; //note that we just take a few numbers, enough to create the number of combinations we might need
    var list = (from i0 in numbers
                from i1 in numbers
                from i2 in numbers
                from i3 in numbers
                from i4 in numbers
                from i5 in numbers
                from i6 in numbers
                from i7 in numbers
                from i8 in numbers
                from i9 in numbers
                select i0 + i1 * 10 + i2 * 100 + i3 * 1000 + i4 * 10000 + i5 * 100000 + i6 * 1000000 + i7 * 10000000 + i8 * 100000000 + i9 * 1000000000).ToList();
    

    This snippet creates a list of more than a 1,000,000 valid unique numbers pretty much instantly.

提交回复
热议问题