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
Related
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.
I have an array initialized as such:
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
I then have a for() loop searching the array for the highest value each time using:
int maxValue = myArray.Max();
int maxIndex = myArray.ToList().IndexOf(maxValue);
It obviously keeps finding 9 as the highest value.
I want it to first set the previously indexed value to a randomized value below the current maxValue but above -1 and continue searching the array for the next maxValue and print it to console.
(If all values reach a value == 0 then the simulation stops) <- this part I know how to do.
Is this possible? If so, how?
I guess this might be what you want. Let me know how it works for you.
using System;
using System.Linq;
public class Program
{
private static Random random = new Random();
public static void Main()
{
int[] myArray = new int[] {9, 8, 7, 3, 4, 5, 6, 2, 1};
Simulate(myArray);
}
static void Simulate(int[] myArray)
{
int maxValue = myArray.Max();
Console.WriteLine(string.Join(" ",myArray));
var continueSimulation = true;
do{
int maxIndex = myArray.ToList().IndexOf(maxValue);
var randomValue = random.Next(0, maxValue);
myArray[maxIndex] = randomValue;
maxValue = myArray.Max();
if (maxValue == 0)
continueSimulation = false;
Console.WriteLine(string.Join(" ",myArray));
}while(continueSimulation);
}
}
You can check it out on this fiddle.
Hope this helps!
If you want to find the second max, you can mark the position of the first one and continue with your same approach. How can be done? 1- initialize an array of bool with the same length of the array where you want to find the max, then find the first max and mark that position in the second array with true, if you want the second max, make a loop through the array asking for the max and if that element is not marked in the second array of bool. Finally you will get the second max .
Another idea is taking the values in a list and once you find the max, remove the max from the list to continue with the same algorithm but with an array of less values
static int Max(int [] num)
{
int max = num[0];
for(int i = 0; i < num.Length; i ++)
{
if(num[i] > max)
max = num[i];
}
return max;
}
static int SecondMax(int[]a)
{
if(a.Length < 2) throw new Exception("....");
int count = 0;
int max = Max(a);
int[]b = new int[a.Length];
for(int i = 0; i < a.Length; i ++)
{
if(a[i] == max && count == 0)
{
b[i] = int.MinValue;
count ++;
}
else b[i] = a[i];
}
return Max(b);
}
Honestly, the question feels a bit unusual, so if you share why you're trying to do this, maybe someone could suggest a better approach. However, to answer your original question, you can just use .NET's random number generator.
int[] myArray = new int[] { 9, 8, 7, 3, 4, 5, 6, 2, 1 };
Random random = new Random();
for (int max = myArray.Max(); max > 0; max = myArray.Max())
{
int index = myArray.IndexOf(max);
DoSomething(max);
myArray[index] = random.Next(0, max);
}
From the MSDN doco on Random, the upper bound is exclusive, which means that it will generate a random number between 0 and max-1, unless max==0, in which case it will return 0.
I am doing with a GUI button. When user click it, it will get number or a word randomly. I know how to do it with just numbers,but i don't know how to deal with both words and numbers.
int[] numbers = new int[5] { 100, 500, 1000, 5000, 20000};
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];
button1.Text = randomNumber.ToString();
One solution for the string would be to create a List of string you want to display, and then get the random number by Random.Next() to display the string in that particular index. Something like:
List<string> words = new List<string> { "Dog", "Cat", "Bird", "Monkey" };
Random rnd = new Random();
... and then in your implementation of the Button Click
int index = rnd.Next(words.Count); //important to limit the random result by the number of the words available
string randomString = words[index]; //Here it is
button1.Text = randomString;
I've got an integer that I'd like to assign a value to by using Random.
The randomly chosen number must be divisable by 2 or 5 (or both).
For divisable only by two I would just multiply the Random result * 2, but it's not an option here.
How to do this?
edit:
I came up with this code, it's probably very inefficient though:
static void Main(string[] args)
{
int[] tab = new int[5];
Random random = new Random();
int i = 0;
while (i < tab.Length)
{
int tempInteger = random.Next(101);
if (tempInteger % 2 == 0 || tempInteger % 5 == 0)
{
tab[i] = tempInteger;
i++;
}
}
}
What about something like:
void Main()
{
var xs = new[] { 2, 5 };
var rand = new Random();
var r = xs[rand.Next(0, xs.Length)] * rand.Next(SOME_UPPER_BOUND);
}
The idea is that we first choose either 2 or 5, then multiply that choice by an arbitrary number between 0 and SOME_UPPER_BOUND.
I tested it with SOME_UPPER_BOUND = 101, and empirically r is either divisible by 2, 5, or 10.
If you want equal probabilities of divisibility by either 2, 5, or both (i.e. 10), then change the first line to var xs = new[] {2, 5, 10}.
It's not explicitly meantioned in the question but I would expect a behavior where each result number is generated with same probability. The solution suggested by #RodrickChapman works well but for example number 10 will appear in the result twice more often than number 6. It's due to the fact, that 10 can be generated as 2*5 and also as 5*2 but number 6 can be only generated as 2*3
First let's make simple observation: each result number must end with number 0, 2, 4, 5, 6 or 8. All we need to do is to randomly choose from these numbers and add this number to some random number which ends with 0 (0, 10, 20, 40, ....).
int upperBound = 100;
var random = new Random();
var choices = new[] { 0, 2, 4, 5, 6, 8 };
var baseNumber = random.Next(0, upperBound / 10) * 10;
var lastDigit = choices[random.Next(choices.Length)];
var result = baseNumber + lastDigit;
Well you could always multiply it by 10 - that way it will always be divisible by 2 and 5.
In that case, I would create two random numbers like this. One is the base one, another one ranges from 0 to 2, which will be mapped to multiply of 2, 5, and 10 respectively, and then multiply the two of them such as this:
Random rand = new Random();
int baseInt = rand.Next(101);
int choiceInt = rand.Next(0, 3);
List<int> mapInts = new List<int>() { 2, 5, 10 };
int finalInt = baseInt * mapInts[choiceInt];
the finalInt would always be divisible by 2, 5 or 10.
Better solution is to multiply random generated number to 2 or 5.
Or you can generate array of number which is divisible and randomly select them from array by randomly generated index.
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. (...)