5

I'm doing a C# coding. In my coding, I need to generate a random list of numbers. Normally, if we create a random, we need to select the range of the number. However for my case, I need to create a random number from an array. Any idea? I am using XAML and C#.

private void Submit_Click(object sender, RoutedEventArgs e)
    {         
        int[] numbers = new int[5] {32, 67, 88, 13, 50};
        Random rd = new Random();
        //int myNo = rd.Next(numbers[])?                    
    }

EXTRA: Each time i click the submit button, a random number of numbers[] will selected. How can i make sure the number is not repeated. For example: 1st click, myNo = 67; 2nd click, myNo = 50; 3rd click, myNo = 88; 4th click, myNo = 32; 5th click, myNo = 13. Thanks!

Nerdynosaur
  • 1,798
  • 9
  • 32
  • 61
  • Please read http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number and also clarify expected result of `rd.Next(numbers)` – Alexei Levenkov Apr 22 '13 at 05:24
  • What means "a random number from an array"? Do you need an array of random numbers? A random number for each item in the array? How is the random number related to the array? Should there be some repeatability? Why not just create a random number? ... – Stefan Steinegger Apr 22 '13 at 06:41

9 Answers9

14

You can create a random number whihch would represent the index from the array. Access the array element from that random index and you will get your number, since all your numbers in the array seems to be distinct.

int[] numbers = new int[5] { 32, 67, 88, 13, 50 };
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];

EDIT: (Thanks to @Corak) You can generate random Index based on array length, that would make it dynamic and work for any array's length.

int randomIndex = rd.Next(0, numbers.Length);

Edit 2: (For extra part of question).

You need to maintain a list of unique index numbers at class level. So your code would be something like:

Random rd = new Random(); //At class level
List<int> uniqueIndices = new List<int>(); //At class level
private void Submit_Click(object sender, RoutedEventArgs e)
{         
    int[] numbers = new int[5] {32, 67, 88, 13, 50};
    int randomIndex = rd.Next(0, numbers.Length);
    while(list.Contains(randomIndex)) //check if the item exists in the list or not. 
    {
        randomIndex = rd.Next(0, numbers.Length);
    }
    list.Add(randomInex);
    //...rest of your code. 


}
Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • 1
    I'd suggest getting rid of the `5`: `int[] numbers = new int[] { 32, 67, 88, 13, 50 };` (maybe even `var numbers = new[] { 32, 67, 88, 13, 50 }`) and `int randomIndex = rd.Next(0, numbers.Length);` – Corak Apr 22 '13 at 06:17
  • 1
    @Corak, that is a good suggestion and would be useful for OP for any length array. – Habib Apr 22 '13 at 06:19
  • thx for the array.length!! btw, i update my question, please feel free to take a look. C= – Nerdynosaur Apr 22 '13 at 06:40
  • @0070, I have edited the answer, usually its a good practice if you ask all the question in the first go, since SO is not like a forum. – Habib Apr 22 '13 at 06:46
  • I would actually see my [answer](http://stackoverflow.com/questions/16139925/how-to-create-a-random-number-from-array/16140135#16140135) where I extract the keeping of random indexes to another class. That is not the responsibility class handling the click event. – Tomas Jansson Apr 22 '13 at 07:01
  • noted. Acutally i'm doing practice while i'm asking the question. Thanks anyway – Nerdynosaur Apr 22 '13 at 07:07
3
Random r = new Random();
int index = r.Next(0, 5);

int randomNum = numbers[index];

This will give you random numbers between 0 and 4 which can be used to index your array and in turn pull random values from the array

TGH
  • 38,769
  • 12
  • 102
  • 135
1

Here is a parametric way:

randIndex = rd.Next(0, numbers.Length);
int myNo = numbers[randIndex];
fatihk
  • 7,789
  • 1
  • 26
  • 48
1

I would create a class that would represent an random enumerable and than use then extension methond First to generate the first index you should use in the array. It would look something like this:

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = new int[5] { 32, 67, 88, 13, 50 };
        var randomEnumerable = new RandomEnumerable(0, numbers.Length);
        int i = 0;
        while (i < numbers.Length)
        {
            var nextIndex = randomEnumerable.First();
            var number = numbers[nextIndex];
            Console.WriteLine(number);
            i++;
        }
        Console.ReadLine();
    }
}

class RandomEnumerable : IEnumerable<int>
{
    private readonly int _max;
    private readonly int _min;
    private Random _random;

    public RandomEnumerable(int min, int max)
    {
        _max = max;
        _min = min;
        _random = new Random();
    }

    public IEnumerator<int> GetEnumerator()
    {
        while (true)
        {
            yield return _random.Next(_min, _max);
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}
Tomas Jansson
  • 22,767
  • 13
  • 83
  • 137
0

Just create a random index as usual, and index into the array with that value instead of returning it directly.

Pieter Geerkens
  • 11,775
  • 2
  • 32
  • 52
0

You have to generate array index randomly to get a random number from your array.

just apply the random function to generate numbers between the range of the array index(0, array.length - 1)

tausun
  • 2,154
  • 2
  • 24
  • 36
0

You could create a Random number and then use the mod operator % by 5 and use that as the index for your array.

Eg. modRd = rd % 5; randomNumber = numbers[modRd];

Nashibukasan
  • 2,028
  • 23
  • 37
0

This will create a random and unique number from array

 public class Shuffler
 {
    Random randomNumber;
    public Shuffler()
    {
        randomNumber = new Random();
    }

    /// <summary>
    /// Shuffling the elements of Array
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="array"></param>
    public void Shuffle<T>(IList<T> array)
    {
        for (int n = array.Count; n > 1; )
        {
            int k = randomNumber.Next(n); //returning random number less than the value of 'n'
            --n; //decrease radom number generation area by 1 
             //swap the last and selected values
            T temp = array[n];
            array[n] = array[k];
            array[k] = temp;
        }
    }
 }
Mogli
  • 1,972
  • 11
  • 34
  • 67
0

You could create a string with all the values combined and then obtain the hashcode of it. This hashcode can then be used to seed the random.

Using the HashCode approach makes the seed more dependent on a data of you array.

    public static void Main()
    {
        int[] numbers = new int[5] { 32, 67, 88, 13, 50 };


        StringBuilder valuesToBeHashed = new StringBuilder();
        for (int i = 0; i < numbers.Length; i++)
        {
            valuesToBeHashed.Append(numbers[i] + ",");
        }

        Random rd = new Random(valuesToBeHashed.GetHashCode());
        Console.WriteLine("Hashcode of Array : {0} ",valuesToBeHashed.GetHashCode());
        Console.WriteLine("Random generated based on hashcode : {0}", rd.Next());
    }
Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39