已知Random.Next(1,10),产生1至100不重复的随机数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace www.cnblogs.com.rock_chen
{
    class Program
    {
        /// <summary>
        /// 已知Random.Next(1,10),产生1至100不重复的随机数据
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            GenerateRandom generateRandom = new GenerateRandom();
            var result = generateRandom.Calc();
            Console.WriteLine(string.Join(",", result));
            Console.WriteLine();
            Console.WriteLine(string.Join(",", result.OrderBy(p => p).ToArray()));
            Console.Read();
        }
    }

    public class GenerateRandom
    {
        Random random = new Random();

        public int[] Calc()
        {
            int[] ary = new int[100];
            int count = 0;
            int currentIndex = 0;
            int k = 0;
            while (count < 100)
            {
                var index = RandomInt();
                if (ary[currentIndex] == 0)
                {
                    ary[currentIndex] = index;
                    ary[index - 1] = currentIndex + 1;
                    currentIndex = index - 1;
                    count = 2;
                    continue;
                }
                if (ary[index - 1] == 0 && currentIndex != index - 1)
                {
                    ary[index - 1] = ary[currentIndex];
                    ary[currentIndex] = index;
                    currentIndex = index - 1;
                    count++;
                }
                else
                {
                    while (k < 100 && ary[k] > 0)
                    {
                        k++;
                    }
                    if (currentIndex != k && k < 100)
                    {
                        ary[k] = ary[currentIndex];
                        ary[currentIndex] = k + 1;
                        currentIndex = k;
                        count++;
                    }
                }
            }
            return ary;
        }

        public int RandomInt()
        {
            return (random.Next(1, 10) - 1) * 10//10-80十位数
                + random.Next(1, 10) + random.Next(1, 10) - 1 //1_17 
                + (random.Next(1, 10) & 3); //0-3
        }
    }
}

转载于:https://www.cnblogs.com/rock_chen/archive/2012/04/15/2450112.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值