一道生成不重复随机数字的C#笔试编程题

当时写在纸上的程序没有验证输入,出面试公司没多久就突然想起来这点了,囧啊!

不过当时笔试的时候想到写异常处理了。

回来上机整理了一下程序,才发现原来还会用到递归的。

当时面试官边说边出的题,问他数字是不是连续的他说这点可以忽略,不然下面的程序还可以简化,另外错误提示其实也可以再友好点,比如提示有效范围。

如果数据源中的数据本身有重复的话,下面的程序也不适用。

代码如下:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //已知一组数字,假设最大为1000个,这里就不写1000个了
                List<int> srcArr = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };

                //输入一个数 输出这组数中指定数量的不重复数字
                getDistinctRandomNum(srcArr);
            }
            catch (Exception ex)
            {
                //记录异常
            }
        }

        /// <summary>
        /// 已知一组数字
        /// 输入一个数
        /// 输出这组数中指定数量的不重复数字
        /// </summary>
        /// <param name="srcArr">数据源</param>
        static void getDistinctRandomNum(List<int> srcArr)
        {
            int maxIndex = srcArr.Count - 1;
            string inputNumStr = Console.ReadLine();//输入

            if (new Regex(@"^\d{1,}$").IsMatch(inputNumStr))//验证是否为数字
            {
                int inputNum = Int32.Parse(inputNumStr);
                if (inputNum <= 0 || inputNum > maxIndex)//验证范围
                {
                    Console.WriteLine("输入的数字超过范围,请重新输入!");
                    //递归调用 准备下次输入、输出
                    getDistinctRandomNum(srcArr);
                }
                else
                {
                    List<int> resultArr = new List<int>();
                    List<int> indexArr = new List<int>();
                    int tempIndexVal;

                    //生成有效数目范围内的,指定数目不重复随机数
                    while (resultArr.Count < inputNum)
                    {
                        tempIndexVal = new Random().Next(0, maxIndex);
                        if (!indexArr.Contains(tempIndexVal))
                        {
                            indexArr.Add(tempIndexVal);
                            resultArr.Add(srcArr[tempIndexVal]);
                        }
                    }

                    //输出
                    foreach (int item in resultArr)
                    {
                        Console.WriteLine(item);
                    }

                    //递归调用 准备下次输入、输出
                    getDistinctRandomNum(srcArr);
                }
            }
            else
            {
                Console.WriteLine("输入不是零或正整数,请重新输入!");
                //递归调用 准备下次输入、输出
                getDistinctRandomNum(srcArr);
            }
        }
    }
}

 

posted @ 2014-02-14 16:33  志在必得Shaun  阅读(673)  评论(0编辑  收藏  举报