Performance issue with generation of random unique numbers

前端 未结 10 615
星月不相逢
星月不相逢 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:33

    Looking at the solutions already posted, mine seems fairly basic. But, it works, and generates 1million values in approximate 1s (10 million in 11s).

    public static void generateIdentifiers(int quantity)
    {
        HashSet uniqueIdentifiers = new HashSet();
    
        while (uniqueIdentifiers.Count < quantity)
        {
            int value = random.Next(111111111, 999999999);
            if (!value.ToString().Contains('0') && !uniqueIdentifiers.Contains(value))
                uniqueIdentifiers.Add(value);
        }
    }
    

提交回复
热议问题