I am trying to replace random number with pictures. for example If random number is 1 show picture black.jpg:
Cache[diceKey] = r.Next(1, 5); // random (1-4)
if (r.Next(1, 2) == 1 )
image.BackImageUrl = "Images/black.png";
is there any solutions that I can show my picture if random number is 1?
Store your image urls in an array. Generate a random index to access the image:
string[] imageUrls = new [] { "foo.png", "bar.png", "foobar.png" };
// ...
Random r = new Random();
image.BackImageUrl = imageUrls[r.Next(imageUrls.Length)];
Update (still not getting the issue, though)
Only set a certain image if the generated random number is 1:
int i = r.Next(1, 5); // random (1-4)
Cache[diceKey] = i;
if (i == 1)
{
image.BackImageUrl = "Images/black.png";
}
As I already said in my comment r.Next(1, 2) will always return 1, so you will always show that black image...
I think you should change your code to this:
var randomValue = r.Next(1, 5); // random (1-4)
Cache[diceKey] = randomValue;
if (randomValue == 1)
image.BackImageUrl = "Images/black.png";
else
image.BackImageUrl = "";
Related
I'm new to the programming world and I would appreciate some help to finish an exercise.
Exercise goal: User guesses 10 numbers. The numbers are then stored in an array. Array is called
"userGussedNumbers" in my program(it's not included down below). Then the program will
generate 4 random numbers and store in an array "generatedWinningNumber". Now the program
will compare the arrays and displays matches.
Problem i have: How do I compare both of these arrays and print out the winning numbers? There will be 4
winning numbers. You can see my solution down below but it stops when it gets the first
match. I want it to keep scanning for more matches and display all matches if any matches
found ofc.
private static void Main()
{
Random randomNumber = new Random();
int[] generatedWinningNumber = new int[4];
int temp;
// Console.WriteLine("\nThese are the winning number...");
for (int i = 0; i<generatedWinningNumber.Length; i++)
{
temp = randomNumber.Next(1, 26);
generatedWinningNumber[i] = temp;
if (userGussedNumbers.Intersect(generatedWinningNumber).Any())
{
Console.WriteLine("\n Number {0} matched", userGussedNumbers[i]);
}
else
{
Console.WriteLine("No match!");
}
}
}
If I understand your question correctly, you are saying that if one value is guessed correctly then all of them say they were guessed correctly.
I believe this is due to the .Intersect(...).Any(). I am not an expert on this function, but I believe it is returning true if any value in the arrays match. Perhaps just use .Contains() from System.Linq
using System.Linq;
Random randomNumber = new Random();
//int[] userGuessedNumbers = new int[10] { 9, 2, 15, 4, 11, 6, 7, 8, 2, 10 };
int[] generatedWinningNumber = new int[4];
for (int i = 0; i < generatedWinningNumber.Length; i++)
{
//Removed unnecessary temp
generatedWinningNumber[i] = randomNumber.Next(1, 26);
//An easier way to format most strings in C# is by using $"string here {variablesHere}"
if (userGuessedNumbers.Contains(generatedWinningNumber[i]))
Console.WriteLine($"\nNumber {generatedWinningNumber[i]} matched!");
else
Console.WriteLine($"\nNo match to {generatedWinningNumber[i]}!");
}
The Intersect method will give you a sequence with all the current winning numbers, so you can also try something like this.
Random randomNumber = new Random();
int[] generatedWinningNumber = new int[4];
for (int i = 0; i<generatedWinningNumber.Length; i++)
{
generatedWinningNumber[i] = randomNumber.Next(1, 26);
}
var winningNumbers = userGussedNumbers.Intersect(generatedWinningNumber);
if (winningNumbers.Any())
{
foreach(int number in winningNumbers) {
Console.WriteLine("\nNumber {0} matched", number);
}
}
else
{
Console.WriteLine("No match!");
}
This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.
Without the if statement it works, but it won't fill the range needed.
fixed the code, now works OK, the initial value in array was the problem. now I ged needed 0-29 values
public partial class Form1 : Form
{
int[] rndCards = new int[30];
public Form1()
{
InitializeComponent();
richTextBox1.Text = #"random numbers";
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
rndCards = new int[30];
richTextBox1.Clear();
Random rnd = new Random();
while (i < 30)
{
int cardTest = rnd.Next(0, 30);
while (rndCards.Contains(cardTest))
{
cardTest++;
if (cardTest == 31)
{
cardTest = 1;
}
}
rndCards[i] = cardTest;
i++;
}
i = 0;
while (i < 30)
{
rndCards[i] = rndCards[i] -1;
richTextBox1.Text += rndCards[i] + ", ";
i++;
}
}
}
You problem lies in the simple fact that the array already contains the number 0 when you create it (because each item of an array is initialized to the default value for its member's type) That's why you should start your i from 1 and not zero.
int i = 1;
Alternative Simpler Approach:
You can do this as a simple random number generation:
Random rnd = new Random();
rndCards = Enumerable.Range(0, 30).OrderBy(x => rnd.Next()).ToArray();
foreach(var card in rndCards)
{
// do something
}
rnd.Next(0,30) would return a random number from 0-29.
From the documentation for Random.Next(Int32, Int32):
The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.
Use int cardText = rnd.Next(0, 31);, and this should solve your issue.
The upper bound is exclusive (C# Random.Next - never returns the upper bound?).
int cardTest = rnd.Next(0, 31);
I have been searching for an answers to my problem but I can't find any solutions.
I writing a program where the user enter name, last name, and social number for five students. When that's done a random number will get handed to each of the five students the user has typed in. But the problem is that two students can not have the same random number. I know with 1-10000 the chances is low, but this is my task.
This is my code where I have tried to fix the problem but I can't get it to work.
while (antal != ggr)
{
string name = Interaction.InputBox("Write name: ");
string lastname = Interaction.InputBox("Write last name: ");
string socialnr = Interaction.InputBox("Write social number: ");
while (a != false)
{
foreach (int item in uniqNum)
{
if (item == _rnd)
{
a = true;
}
else
{
_rnd = rnd.Next(1, 10000);
uniqNum.Add(_rnd);
a = false;
}
}
}
ggr++;
_Studens.Add(new student(name, lastname, socialnr, _rnd));
}
Generate a list containing all the random numbers you wish to pick from. Then, choose an index randomly from that list, add the resultant number to a separate list, and remove the indexed element from the list of all numbers.
This will work for smaller ranges of numbers. If you wanted a unique random number in larger ranges, this method is probably not appropriate. In that case, consider generating GUIDs and converting them to their 128-bit numeric representation.
var allNumbers = Enumerable.Range(1, 10000).ToList();
var randomNumbers = new List<int>();
var random = new Random();
const int studentCount = 5;
for (int i = 0; i < studentCount; i++)
{
int randomIndex = random.Next(0, allNumbers.Count);
randomNumbers.Add(allNumbers[randomIndex]);
allNumbers.RemoveAt(randomIndex);
}
What about if you generate the number first, then use the Contains() method to check if the number already exists? If it does, generate the number again. Something like this:
int number = 0;
List<int> numberArray = new List<int>();
while (true)
{
Random r = new Random();
number = r.Next(1, 1000);
if (!numberArray.Contains(number))
{
break;
}
}
Random r = new Random();
Enumerable.Range(1,10000).OrderBy(n => r.Next()).Take(5);
Generating a random password is easy. but generating a batch is more difficult.
public static string getRandomPassword(int letters, int getallen) {
//int letters = 8;
//int getallen = 5;
char[] letterdeel = new char[letters];
int minGetal = (int)Math.Pow(10, getallen - 1);
int maxGetal = (int)Math.Pow(10, getallen);
string password;
Random r = new Random();
int test = (int)(DateTime.Now.Ticks);
for (int i = 0; i < letters; i++) {
r = new Random((int)(DateTime.Now.Ticks) + i);
bool capital = r.Next(2) == 0 ? true : false;
if (capital) {
letterdeel[i] = (char)r.Next(65, 91);
} else {
letterdeel[i] = (char)r.Next(97, 123);
}
}
password = new string(letterdeel);
password += r.Next(minGetal, maxGetal);
return password;
}
this is my method, the passwords should be in a certain letter-number format.
this works fine, however if i have a for loop pulling 100 passwords from this method, in my array i have 5-8 the same passwords, then again 5-8 the same pass.
i know WHY this is, because of the random function and the clock it depends on, but how do i fix this?
Move Random r to outside the method if you are repeatedly calling it. You are going to be hitting it several times in the same relative timeframe, so you are going to be generating the same seeds. You also want to get rid of the line below. It is unnecessary, and (again), with the nature of DateTime.Now, you would just continue to generate the same sequence of "random" numbers.
r = new Random((int)(DateTime.Now.Ticks) + i);
Define your random number generator as a static outside of the function.
How can I get true randomness in this class without Thread.Sleep(300)?
Use a set rather than whatever collection you store into and don't loop 100 times but until the set has 100 items in it.
Random r = new Random();
int sayi = r.Next(1, 49);
textBox1.Text = sayi.ToString();
This code shows the first random number in textbox1, but I also need to get the output for the other textboxes as well:
(first click)--->Textbox1: 3
(second click)--->textbox2: 24
(third click)---> textbox3: 32
// Declare Click Counter Global
private int clickCounter = 0;
// On Button Click Event
Random r = new Random();
if(clickCounter == 0)
{
textBox1.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
if(clickCounter == 1)
{
textBox2.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
if(clickCounter == 2)
{
textBox3.Text = Convert.ToInt32(r.Next(1,49));
clickCounter++;
}
This code block gives you what you want.
If you just have text boxes on your form (so that they are effectively fields in your Form class), you can add an int counter field to your class, initialize it to 0, and have (note: untested code):
Random r = new Random();
int sayi = r.Next(1, 49);
string textBoxName = "textBox"+counter;
FieldInfo fi = GetType().GetField(textBoxName);
TextBox currentTextBox = (TextBox)fi.GetValue();
currentTextBox.Text = sayi.ToString();
couter++;
plese note that this approach is rather ugly. It would be nicer to have these text boxes in a list or array and find them using the index instead of using the name of the field.