Generate Random number in C# [duplicate] - c#

This question already has answers here:
How do I generate a random integer in C#?
(31 answers)
Closed 6 years ago.
I am wanting to generate a random number between 1 and 10. Yet I am getting a couple of errors.
public Form1()
{
InitializeComponent();
}
int randomNumber = (0, 11);
int attempts = 0;
public int RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
}
}
it is all on the 0, 11 under the comma is says --> struct System.Int32 represents a 32-bit signed integer <--. Under the 11 it says --> Identifier expected Syntax error, ',' expected <--. Now if I just have like int randomNumber = 0; then it will work fine, still have multiple guesses and the guess count adds up like it should, and have the too high too low labels. just the number will always be 0.
Also how can I make it to where I don't have to click the guess button, I can just hit enter on the keyboard?
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";
else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
else
{
label1.Text = "You won.";
textBox1.Enabled = false;
label2.Text = "Attempts: 0";
textBox1.Text = String.Empty;
MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
attempts = 0;
label2.Text = "Attempts: " + attempts.ToString();
return;
}
attempts++;
label2.Text = "Attempts: " + attempts.ToString();
}
catch { MessageBox.Show("Please enter a number."); }
}

To generate a Random number you have to usw the System.Random class. Your syntax can look something like this :
System.Random rng = new System.Random(<insert seed if you want>);
int randomNumber = rng.Next(1,11);
You have to do rng.Next(1,11) since the lower bound is include (1 is a possible result) and the upper bound is exclude (11 isnt getting added into the pool oft possible results).
To do implement your Enter shortcut you have to add a method to your Forms KeyPress event in which you call the button1_clicked method.
button1_Clicked_1(this, System.EventArgs.Empty);
At last you have to set your forms "KeyPreview" property to true.

You can use something like the below code to generate random number between 1 to 10
Random randomNumberGenrator = new Random();
int num = randomNumberGenrator.Next(10) + 1;

Take a look at this.
Use the Random class in order to generate a random number.
private Random _rnd = new Random();
private int RandomNumber
{
get
{
return _rnd.Next(0,11);
}
set
{
this = value;
}
}

Related

What should I do in order to display how many loops it takes to get a favourable number?

Im new to programming and Im currently attempting to make a dice program, where the user can input how many throws they would like to do and then a list will display how many throws it took to get a specific number, in this case that number is 6 (later on I'd like to make it for all numbers 1-6) How should I go about doing this?
Im currently trying to use an if-statement to recognize when a specific number is rolled, currently I want the program to recognize the number 6, but im a bit unsure how to display the amount of rolls it took to get that number, in a list, and also keeping the loop going until all rolls have been executed.
private void Btnkast_Click(object sender, EventArgs e)
{
bool throws;
int numberofthrows = 0;
int dice;
Random dicethrow = new Random();
throws = int.TryParse(rtbantal.Text, out numberofthrows);
int[] list = new int[numberofthrows];
for (int i = 0; i <= numberofthrows; i++)
{
dice = dicethrow.Next(1, 7);
if (dice == 6)
{...}
}
}
Also, the only reason I use tryparse is to prevent crashes when having to handle with string-values.
I have written this for you using a C# Console Application, but I'm sure you will be able to edit it to fit your requirements for Windows Forms.
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
Random rnd = new Random(); // create Random object
Console.WriteLine("Enter a number between 1 and 6: "); // prompt user to enter a number between 1 and 6
int chosenNumberInt;
var chosenNumber = int.TryParse(Console.ReadLine(), out chosenNumberInt); // check to see if user actually entered a number. If so, put that number into the chosenNumberInt variable
Console.WriteLine("How many rolls would you like?"); // prompt user to enter how many rolls they would like to have
int chosenRollsInt;
var chosenRolls = int.TryParse(Console.ReadLine(), out chosenRollsInt);
Console.WriteLine(); // to create space
Console.WriteLine(); // to create space
Console.WriteLine("Chosen Number = " + chosenNumberInt + " --- Chosen Rolls = " + chosenRollsInt); // show user what they entered
Console.WriteLine("------------");
int count = 0;
int numberRolled = 0;
var lstRolls = new List<int>(); // create list object
for(int i = 1; i <= chosenRollsInt; i++)
{
count++;
int dice = rnd.Next(1, 7);
numberRolled = dice;
lstRolls.Add(numberRolled); // add each roll to the list
Console.WriteLine("Roll " + i + " = " + numberRolled); // show each roll
}
var attempts = lstRolls.Count; // how many rolls did you do
var firstIndexOfChosenNumber = lstRolls.FindIndex(x => x == chosenNumberInt) + 1; // have to add 1 because finding the index is 0-based
Console.WriteLine("-------------");
if(firstIndexOfChosenNumber == 0)
Console.WriteLine("The chosen number was " + chosenNumberInt + " and that number was NEVER rolled with " + chosenRollsInt + " rolls.");
else
Console.WriteLine("The chosen number was " + chosenNumberInt + " and the number of rolls it took to hit that number was " + firstIndexOfChosenNumber);
}
}
Something that I didn't add would be the validation to ensure that the user does indeed enter a number between 1 and 6, but you can do that I'm sure.
I have created a DotNetFiddle that proves this code does work and even shows you each roll.
Let me know if this helps or if you need any more assistance.
UPDATE
Based on your comment on my original post, I have edited my code to allow the user to enter the number they want, along with how many rolls. Then, once all of the rolls have been completed, I find the index of the first occurrence of the number they selected in the beginning.
Let me know if this is what you want.
Read the comments I added in the code
private void Btnkast_Click(object sender, EventArgs e)
{
bool throws;
int numberofthrows = 0;
int dice;
Random dicethrow = new Random();
throws = int.TryParse(rtbantal.Text, out numberofthrows);
List<int> list = new List<int>(); //I changed this to a list
for (int i = 0; i < numberofthrows; i++)
{
dice = dicethrow.Next(1, 7);
list.Add(dice); //add every roll to the array to check later the values if you want
if (dice == 6)
{
//Print that you found 6 at the roll number list.Count
Console.WriteLine("Found 6 at roll number: " + list.Count);
break; //probably break the loop so you won't continue doing useless computation
}
}
}

Random Number Generator using C#

I'm needing to create random numbers based on the number of random numbers needed by a user.
The user can then save those random numbers to a file when the save to file button is clicked.
After that, the program allows the user to open the same file, but this time, the file opened needs to display how many random numbers within a specific range were created.
The ranges are: (0-19, 20-39, 40-59, 60-79, and 80-99).
So far I'm able to create one random number and list the same number over the number of times entered by the user, but unfortunately:
The random numbers created need to all be random through the number of iterations created by the user.
I don't know how to display the numbers within their respective range.
I can't display the numbers properly.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void RandNumbtextBox_TextChanged(object sender, EventArgs e)
{
}
private void saveFileButton_Click(object sender, EventArgs e)
{
double randomNumber = double.Parse(RandNumbtextBox.Text);
Random r = new Random();//random number object
int random = r.Next(1, 10);// random number 1
if (saveFileDialog.ShowDialog()== DialogResult.OK)
{
StreamWriter outputFile;
outputFile = File.CreateText(saveFileDialog.FileName + ".txt");
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(random.ToString());
}
outputFile.Close();
}
else
{
MessageBox.Show("op cancelled");
}
}
private void openFileButton_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
StreamReader inputFile;
inputFile = File.OpenText(openFileDialog.FileName);
int sum = 0;
while (!inputFile.EndOfStream)
{
sum += int.Parse(inputFile.ReadLine());
}
inputFile.Close();
MessageBox.Show(sum.ToString());
}
else
{
MessageBox.Show("op cancelled");
}
}
}
Thanks to John I was able to figure out the first issue of the question. Generating the random number issue and write them to file.
I'm still unable to:
*Display the numbers within their respective range.
I can't display the numbers properly.
OP, you are assigning the random number once:
int random = r.Next(1, 10);// random number 1
And then writing it out randomNumber times:
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(random.ToString());
}
I think your code needs to read:
for(int i = 0; i < randomNumber; i++)
{
outputFile.WriteLine(r.Next(1, 10).ToString());
}
As for counting numbers in ranges: A simple approach might be to create "count" variables for each range, and implement branching logic to increment the correct one depending on the number you're looking at. A more dynamic approach may involve a dictionary, or an array of classes which contain the range and a count value.

cycle never reaching final value

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

how to fill int array that has unique numbers in every index? [duplicate]

This question already has answers here:
Random number generator in C# - unique values
(5 answers)
Closed 9 years ago.
I'm creating a bingo game and I'm using Random to generate random numbers in an int array but my problem here is that sometimes a number is used again in an index. How can I make the numbers in index unique?
Here is my work:
namespace Bingo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random randNum1 = new Random();
int[] random1 = new int[5];
int qwe = 0;
int i = 0;
private void button1_Click(object sender, EventArgs e)
{
Class1 class1 = new Class1();
class1.checker(this);
if (label1.Text == label2.Text || label3.Text == label4.Text) {
label2.Text = randNum1.Next(1, 15).ToString();
label4.Text = randNum1.Next(1, 15).ToString();
}
if (label5.Text == label1.Text || label5.Text == label2.Text) {
label5.Text = randNum1.Next(1, 15).ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
Class1 class1 = new Class1();
class1.SetTwo(this);
for (int i = 0; i < random1.Length; i++)
{
random1[i] = randNum1.Next(1, 15);
label1.Text = random1[0].ToString();
label2.Text = random1[1].ToString();
label3.Text = random1[2].ToString();
label4.Text = random1[3].ToString();
label5.Text = random1[4].ToString();
}
}
}
The problem with looping until you found an unused one is that as the game progresses, you'll take longer and longer to find a valid number. It's theoretically possible that your loop will never end (infinitessimally likely, but still...)
The easiest thing to do is what happens in a real Bingo game. Start from a limited set, and actually remove the item from the set each time you draw. Fill a List or any other dynamic indexed container with your initial possibilities, randomly choose an index from 0 to the size of the list, and then remove the selection out of the list.
This will guarantee that every selection produces a unique result, with no looping.
I figured an illustration of Scott Mermelstein's answer may help:
List<int> AvailableNumbers;
Random random;
private void Form1_Load(object sender, EventArgs e)
{
//Create a list of numbers, 1-14
AvailableNumbers = Enumerable.Range(1, 14).ToList();
random = new Random();
label1.Text = GetNextNumber().ToString();
label2.Text = GetNextNumber().ToString();
label3.Text = GetNextNumber().ToString();
label4.Text = GetNextNumber().ToString();
label5.Text = GetNextNumber().ToString();
}
private int GetNextNumber()
{
//Get a random index within the bounds of AvailableNumbers
var nextIndex = random.Next(0, AvailableNumbers.Count);
var nextNumber = AvailableNumbers[nextIndex];
AvailableNumbers.RemoveAt(nextIndex);
return nextNumber;
}
Another approach is to shuffle the sorted list of numbers:
var numbers = Enumerable.Range(1, 15).OrderBy(i => Guid.NewGuid()).ToArray();
How does this work?
start with a list of integers (Enumerable.Range(1, 15) => [1, 2, 3, ..., 15])
reorder them (OrderBy)
with a "random" index Guid.NewGuid()
Obviously, this will only work, if Guid.NewGuid() doesn't produce consecutive GUIDs, but, I think the default doesn't, since that was a security issue with the first implementations of the GUID algorithm.
(I got the shuffling with GUIDs tip from here:
Randomize a List<T>)
You can use other, more efficient methods to shuffle the "deck", but for Bingo style applications, this should work just fine.
Another idea:
var rand = new Random();
var numbers = Enumerable.Range(1, 15).OrderBy(i => rand.Next()).ToArray();
Since the elements in the starting list are unique, the result is guaranteed to reproduce that property.
everytime you grab a new number, just surround it with this :
int num;
do
{
num = randNum1.Next(1, 15);
}
while(random1.Contains(num))
random1[i] = num;
to guarantee it is unique

Flip a coin problem

I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}

Categories

Resources