C#中生成不重复随机数

如果只是生成一个随机数,C#中的Random函数就足够用了,但如果需要生产若干个随机数,且这些数不能重复,就需要自己来写相应的方法了。

1.使用List<int>来存储随机数,List.Contain方法来判断生成的随机数是否已经存在

以在1-10中取5个不重复的随机数为例

        public List<int> Generate1()
        {
            Random random = new Random();
            List<int> result = new List<int>();
            int temp;
            while (result.Count < 5)
            {
                temp = random.Next(0, 11);
                if (!result.Contains(temp))
                {
                    result.Add(temp);
                }
            }
            return result;
        } 
2.在一个List中中存储所有可能的数,每次随机取出一个,并在List中把它移除

以在1-10中取5个不重复的随机数为例

        public List<int> Generate2()
        {
            List<int> all = new List<int>();
            List<int> result = new List<int>();
            Random random = new Random();

            for (int i = 0; i < 11; i++)
            {
                all.Add(i);
            }

            for (int j = 0; j < 5; j++)
            {
                int index = random.Next(0, all.Count - 1);
                result.Add(all[index]);
                all.RemoveAt(index);
            }

            return result;
        } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值