A few days ago I saw a small problem on the. NET written test set, which asked for a simple algorithm to randomly populate a positive integer from 1 to 100 into an array of length 100.
I'm free to write a little bit today. The code is as follows, the comments are more detailed:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Text.RegularExpressions;6 7 namespaceTestnumber8 {9 class ProgramTen { One //define regular expressions that determine positive integers A Public Static stringRegex ="^[1-9][0-9]*"; - Static voidMain (string[] args) - { the -Console.WriteLine ("Please input a number!"); - stringInputstr =console.readline (); - //determines whether the input is a positive integer, or not, the End method + if(!Regex.IsMatch (Inputstr,regex)) - { +Console.WriteLine ("input format Error!"); A return; at } - //Transform Shaping - intinputnum=Convert.ToInt32 (INPUTSTR); - - //Creating an shaping collection, placing 1-N collections -list<int> numlist =Newlist<int>(); in for(intj =1; J < inputnum+1; J + +) - { to Numlist.add (j); + } - //define a random number instance theRandom r=NewRandom (); * int[] Outputnum =New int[Inputnum]; $ for(inti =0; i < Inputnum; i++)Panax Notoginseng { - //gets a random element of a collection the intK = R.next (0, inputnum-i); + //placing an element into an array AOutputnum[i] =Numlist[k]; the //collection to remove the element + Numlist.removeat (k); - } $ foreach(varIinchoutputnum) $ { -Console.Write (i+","); - } the - }Wuyi } the}
The test exception results are as follows:
The normal results of the test are as follows:
Ok,that ' s all.
A simple algorithm that defines an array of length n, which stores all positive integers of 1 to N in random order, and does not repeat.