Returns n unique random numbers in the range [1, n], inclusive. - CSharp System

CSharp examples for System:Random

Description

Returns n unique random numbers in the range [1, n], inclusive.

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;/*from   www .j a  v  a  2 s  . c  om*/

public class Main{
        /// <summary>
        ///     Returns n unique random numbers in the range [1, n], inclusive.
        ///     This is equivalent to getting the first n numbers of some random permutation of the sequential numbers from 1 to
        ///     max.
        ///     Runs in O(k^2) time.
        /// </summary>
        /// <param name="rand"></param>
        /// <param name="n">Maximum number possible.</param>
        /// <param name="k">How many numbers to return.</param>
        /// <returns></returns>
        public static int[] Permutation(this Random rand, int n, int k)
        {
            var result = new List<int>();
            var sorted = new SortedSet<int>();

            for (var i = 0; i < k; i++)
            {
                var r = rand.Next(1, n + 1 - i);

                foreach (var q in sorted)
                    if (r >= q) r++;

                result.Add(r);
                sorted.Add(r);
            }

            return result.ToArray();
        }
}

Related Tutorials