产生多个随机数 [英] Generating multiple random numbers

查看:97
本文介绍了产生多个随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成25个唯一的随机数,并在控制台中列出它们.数字应至少为10个字符.有什么简单的方法吗?

I want to generate 25 unique random numbers and list them in a console. The numbers should be atleast 10 characters long. Any easy way to do that?

推荐答案

尝试将数字构建为字符串,并使用HashSet来确保它们是唯一的:

Try building the numbers up as strings, and use a HashSet to ensure they are unique:

Random random = new Random();
HashSet<string> ids = new HashSet<string>();

while (ids.Count < 25)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10; ++i)
    {
        sb.Append(random.Next(10));
    }
    ids.Add(sb.ToString());
}

示例输出:


7895499338
2643703497
0126762624
8623017810
...etc...

.NET 3.5中存在类 HashSet 较新.

The class HashSet is present in .NET 3.5 and newer.

这篇关于产生多个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆