Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

random

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.


1 Answers

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.

like image 136
Abion47 Avatar answered Jan 19 '26 11:01

Abion47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!