當時寫在紙上的程序沒有驗證輸入,出面試公司沒多久就忽然想起來這點了,囧啊!面試
不過當時筆試的時候想到寫異常處理了。dom
回來上機整理了一下程序,才發現原來還會用到遞歸的。spa
當時面試官邊說邊出的題,問他數字是否是連續的他說這點能夠忽略,否則下面的程序還能夠簡化,另外錯誤提示其實也能夠再友好點,好比提示有效範圍。blog
若是數據源中的數據自己有重複的話,下面的程序也不適用。遞歸
代碼以下:get
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); } } } }