user7549826
user7549826

Reputation:

Random number generator choosing only between given few numbers in C#

I know how to choose random numbers between two numbers. However I don't know how to make it to choose a random number that I tell it.

This is what I am trying to do. I have 5 integers.

int Hamburger = 5;
int Sandwich = 7;
int ChickenSalad = 10;
int Pizza = 15;
int Sushi = 20;

5,7,10,15,20 are the prices of each food and I want to make it so that it would choose a random number from these chosen numbers. 5,7,10,15,20.

I am new to C# so I don't really know much about this. I found this

randomNoCorss = arr[r.Next(arr.Length)];

in another post but I don't understand it and I don't know how I can put it in my code.

Upvotes: 2

Views: 13286

Answers (4)

Abion47
Abion47

Reputation: 24671

You have to create an array of your possible values and then randomly generate an index for that array:

int Hamburger = 5;
int Sandwich = 7;
int ChickenSalad = 10;
int Pizza = 15;
int Sushi = 20;

Random r = new Random();
var values = new[] { Hamburger, Sandwich, ChickenSalad, Pizza, Sushi };
int result = values[r.Next(values.Length)];

What this does is it takes all of your given values and places them inside an array. It then generates a random integer between 0 and 4 and uses that integer to get a value from the array using the generated integer as the array's index.

Upvotes: 9

Willy David Jr
Willy David Jr

Reputation: 9131

You can do this in LINQ:

int[] intArray = new int[] { 5, 7, 10, 15, 20 };

int result = intArray.OrderBy(n => Guid.NewGuid()).Select(x => x).Take(1)
            .SingleOrDefault();

The result will be random based on your declared array of integers in variable intArray.

Or you can do this by getting the random index of your array:

 int[] intArray = new int[] {5, 7, 10, 15, 20 };
 Random rndom = new Random();
 int index = rndom.Next(0, intArray.Length - 1); //Since int array always starts at 0.
 int intResult = intArray[index];

Let me know if you need more clarifications.

Upvotes: -1

Stanley S
Stanley S

Reputation: 1052

You need to add your values in an array and then you can choose a random number from that array

  int[] myNumbers = new int[] { 5, 7, 10, 15, 20 };
  var random = new Random();
  var numberResult = myNumbers[random.Next(5)];

Upvotes: 0

Hossein Golshani
Hossein Golshani

Reputation: 1897

Full code is:

Random r = new Random();
int[] priceArray = new int[] { 5, 7, 10, 15, 20 };
int randomIndex = r.Next(priceArray.Length);
int randomPrice = priceArray[randomIndex];

Upvotes: 1

Related Questions