Not able to convert Random to int - c#

I'm new to programming and can't figure this bit of code out and why it wont work like someone says here: http://social.msdn.microsoft.com/Forums/en-US/55fb3116-c978-4ac8-9381-a2605e16e256/how-do-you-create-a-random-number-in-c?forum=Vsexpressvcs
private void button1_Click(object sender, EventArgs e)
{
Random Random = new Random();
int randomNumber = random.Next(0, 2);
// int[] Tal = new int[5] { 1, 2, 3, 4, 5 };
// MessageBox.Show( Tal[1] );
string[] Names = { "Lasse", "Mads", "Alberte" };
MessageBox.Show( Names[Random] );
}

You should use randomNumber, not Random:
MessageBox.Show( Names[randomNumber] );
And your Random instance should be assigned to random, not Random:
Random random = new Random();
C# is case sensitive, so random and Random are two differents identifiers.
and btw. Random.Next(0, 2) gives you only 0s and 1s. You should use Random.Next(0, 3) to get values between 0 and 2.
Parameters
maxValue
The exclusive upper bound of the random number returned. (...)

Related

Getting specific random number

i want to generate random number between (1 to 6),is there any way to change the chance of geting number 6 more than other numbers?
for example for this code
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
Let p be probability of any 1..5 numbers and 1 - p is a probability of 6:
//DONE: do not recreate Random
private static Random s_Generator = new Random();
private void pictureBox5_MouseClick(object sender, MouseEventArgs e) {
const double p = 0.1; // each 1..5 has 0.1 probability, 6 - 0.5
// we have ranges [0..p); [p..2p); [2p..3p); [3p..4p); [4p..5p); [5p..1)
// all numbers 1..5 are equal, but the last one (6)
int value = (int) (s_Generator.NexDouble() / p) + 1;
if (value > 6)
value = 6;
label2.Text = value.ToString();
}
That wouldn't be random then. If you wanted to weight it so you would get 6 half the time, you could do this:
m = u.Next(1,2);
if(m == 2)
{
label2.Text = "6";
}
else
{
label2.Text = u.Next(1,5).ToString();
}
Based on what weighting you want you could change it-> 3 instead of 2 get a 33.33% weighting and so on. Otherwise, as the commenter said, you'd have to look into probability distributions for a more mathematically elegant solution.
Depends on how more likely. An easy way (but not very flexible) would be the following:
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,7);
if (m > 6) m = 6;
label2.Text = m.ToString();
}
If you want a totally random distribution of 1...5 and just a skwed 6, then Dmitry's seems best.
If you what to skew ALL the numbers, then try this:
Create a 100 element array.
Fill it with the number 1-6 in proportions based on how often you want the number to come up. (make 33 of them 6, if you want 6 to come up 1/3rd of the time. Four 4s means it'll only come up one in 25 rolls etc. 15 or 16 of each number will make it about evenly distributed, so adjust the counts from there)
Then pick a number from 0...99 and use the value in the element of the array.
You could define the possibility in a percentage of getting each of the numbers in an array:
/*static if applicable*/
int[] p = { (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Ceiling((double)100/6) };
////The array of probabilities for 1 through p.Length
Random rnd = new Random();
////The random number generator
int nextPercentIndex = rnd.Next() % 100; //I can't remember if it's length or count for arrays off the top of my head
////Convert the random number into a number between 0 and 100
int TempPercent = 0;
////A temporary container for comparisons between the percents
int returnVal = 0;
////The final value
for(int i = 0; i!= p.Length; i++){
TempPercent += p[i];
////Add the new percent to the temporary percent counter
if(nextPercentIndex <= TempPercent){
returnVal = i + 1;
////And... Here is your value
break;
}
}
Hope this helps.

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.
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.
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];
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)];
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.

How to set random number to random label

i have int array with 9 numbers and i want to set a random number to a random label, (4 labels). at button click add next random number to next label so i have this code :
int[] CardDeck = new int[9] { 3, 4, 5, 6, 7, 8, 9, 10, 11 };
Random RandomCard = new Random();
int randomIndex = RandomCard.Next(0, CardDeck.Length);
int randomNumber = CardDeck[randomIndex];
if (string.IsNullOrEmpty(L1.Text))
{
L1.Text = Convert.ToString(randomNumber);
return;
}
if (string.IsNullOrEmpty(L2.Text) && Convert.ToInt32(L1.Text) > 0)
{
L2.Text = Convert.ToString(randomNumber);
}
but something is wrong it sets same numbers to two labels.
This is because you are using the same randomNumber variable.
You should generate another random number for the remaining label.
int randomLabel1 = CardDeck[RandomCard.Next(0, CardDeck.Length)];
int randomLabel2 = CardDeck[RandomCard.Next(0, CardDeck.Length)];
Then you should use these two variables with the labels accordingly.
Please note that this approach does not guarantee unique random numbers. Same numbers for both labels may occur.
PS: You can also use the same randomNumber to store a new random number, but remember to do it AFTER setting the first label:
int randomNumber = CardDeck[RandomCard.Next(0, CardDeck.Length)];
//Set first label
randomNumber = CardDeck[RandomCard.Next(0, CardDeck.Length)];
//Set second label

Non duplicate random numbers in C# [duplicate]

This question already has answers here:
Random.Next returns always the same values [duplicate]
(4 answers)
Closed 9 years ago.
I am trying to create a range of non duplicate random numbers between 1 - 10, I planned on doing this by storing each random number I made in to an array and then checking that array every time to make sure I ain't already used the number.
My problem is that instead of creating different random numbers such as 1, 2, 3 I just keep getting the same random number over and over.
randomNumber();
Label1.Text = randomRow + "";
randomNumber();
Label2.Text = randomRow + "";
randomNumber();
Label3.Text = randomRow + "";
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
Random randNum = new Random();
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
Problem : everytime you are creating the RandomNumber object in too close time.
When you create a Random object, it's seeded with a value from the system clock. If you create Random instances too close in time, they will all be seeded with the same random sequence.
From Here
When you create a Random object, it's seeded with a value from the
system clock. If you create Random instances too close in time, they
will all be seeded with the same random sequence.
Solution :
move Random randNum = new Random(); outside the function randomNumber().
Try This:
Random randNum = new Random();
public int randomNumber()
{
List<int> numbers = new List<int>();
int num = 0;
num = randNum.Next(1, 11);
if (numbers.Contains(num))
{
num = randNum.Next(1, 11);
}
else
{
randomRow = num;
numbers.Add(num);
}
return randomRow;
}
My best gues is that you are using this in a loop. In this case because you declare
Random randNum = new Random();
evry time this will generate tha same number. Just declare it BEFORE the loop and it should be fine.
Also you should consider a different approch because it is not a good practice. Like:
int[] array = {1,2,3,4,5,6,7,8,9,10};
Random randNum = new Random();
int rand=0;
int temp;
for(int i = 0; i<10;i++)
{
rand = randNum.next(1,10-i);
temp=array[rand];
array[rand]=array[9-i];
array[9-i]=temp;
}

generating integer random numbers in c#

I want to generate 4 digit random number and put it in the text box as serial number of something . how do I do that and yet to some extent be sure I wouldn't get duplicated numbers?
If you want to be sure that you don't get duplicates use a Guid:
Guid guid = Guid.NewGuid(); // however a Guid is not a 4 digit integer
If you want a random number use Random:
Random rnd = new Random();
int randomInt = rnd.Next(1000, 10000)
But note that you should not create the random instance in a loop because it is seeded with the current time. Otherwise you get repeating values. So either pas the random instance as parameter to this method, use a field/property or use the same instance in a loop which was created outside.
The easiest approach to get unique random numbers is to create new numbers if one already exists.
List<int> used = new List<int>();
Random random = new Random();
foreach(thing you want to do)
{
int current = random.Next(1000, 9999);
while(used.Contains(current))
current = random.Next(1000, 9999);
//do something
used.Add(current);
}
or some similar variation on this to meet your needs
Best way to do it is with the Random class:
Random random = new Random();
int result = random.Next(1000, 10000);
You could also use the RNGCryptoServiceProvider class, which gives you more secure random numbers:
RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
byte[] bytes = new byte[4];
csp.GetBytes(bytes);
int yourNum = bytes.Select(x => x % 10).Aggregate(0, (a, b) => (a * 10) + b);
The Random class is used to create random numbers. (Pseudo-random that is of course.)
Example:
Random rnd = new Random();
int num = rnd.Next(1000, 10000); //creates number from 1000 to 9999
You can use HashSet for store generated number and check duplicate
The easiest way to do this is generate a list of all possible choices in order and shuffle it. Then after shuffling the list just go through the list "in order" and the sequence will be random and non repeating.
List<int> numbers = new List<int>(Enumerable<int>.Range(0,10000);
HelperFunctions.Shuffle(numbers); //There are plenty of examples of how to shuffle the list on this site.
foreach(var number in numbers)
{
Console.WriteLine(number.ToString("D4"); //Displays random numbers from 0000 to 9999 but never repeats
}
Like this:
var random = new Random();
var numbers = new List<int>(0);
for (var i = 0; i < 4; i++)
{
var number = random.Next(1000, 10000);
if (numbers.Contains(number))
{
i--;
continue;
}
numbers.Add(number);
}
tbx1.Text = numbers[0].ToString();
tbx2.Text = numbers[1].ToString();
tbx3.Text = numbers[2].ToString();
tbx4.Text = numbers[3].ToString();
This will give you a 4 digit random number.
Random random= new Random();
int RnNum = random.Next(1000,9999);
If you want to be sure that it doesn't get duplicated, then store the generated random values in Session & compare if its already generated. Of course there are other ways, if you don't want to do it the session way, write to a text file or something
You need to keep a record yourself of the numbers that have been generated in Dictionary or Hashset. Like
HashSet<int> generatedValues = new HashSet<int>();
Random rnd = new Random();
int randomInt = rnd.Next(1000,9999);
while(generatedValues.Contains(randomInt))
{
randomInt = rnd.Next(1000,9999);
}
generatedValues.Add(randomint);

Categories