Excerpt from the network
Static voidMain (string[] args) { //The probability of each item is stored in the array . float[] area =New float[4]{ 0.5f, 0.5f, 0, 0 }; //One-time test//Console.WriteLine (Get (area)); //Batch Test int[] result =New int[4]{ 0, 0, 0, 0 }; for(inti =0; I <1770000; i++)//in order to be more convenient than the results, the number of cycles here is 1000 times times the total probability { intn = Get (area);//results of the lotteryresult[n]++;//number of counts drawn} Console.WriteLine ("Results:"); foreach(intTimesinchresult) {Console.WriteLine (times); } console.readline (); } /// <summary> ///Get lottery Results/// </summary> /// <param name= "prob" >The probability of the extraction of each item</param> /// <returns>Returns the position of the array in which the item was pumped</returns> Private Static intGet (float[] prob) { intresult =0; intn = (int) (prob. Sum () * +);//calculate the sum of probabilities and magnify 1000 times timesRandom r =NewRandom (); floatx = (float) R.next (0, N)/ +;//randomly generated numbers for the sum of 0~ probabilities for(inti =0; I < prob. Count (); i++) { floatPre = prob. Take (i). Sum ();//interval Lower bound floatNext = prob. Take (i +1). Sum ();//upper bounds of interval if(x >= pre && x < next)//if within that interval, the return result exits the loop{result=i; Break; } } returnresult; }
C # Lottery algorithm