This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I've run into a strange issue. When I run the following code, each of my text boxes get's filled with the same randomly generated number.
public void diceAdd()
{
int[] die = new int[4];
for(int i = 0; i < total.Length; i++)
{
for (int r = 0; r < die.Length; r++)
{
//Simulates rolling a 6 sided die
Random rand = new Random();
randomNumber = rand.Next(1, 7);
die[r] = randomNumber;
}
int smallest = die[0];
for (int c = 1; c < die.Length; ++c)
{
if (die[c] < smallest)
{
smallest = die[c];
}
}
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
}
strTxt.Text = total[0].ToString();
dexTxt.Text = total[1].ToString();
conTxt.Text = total[2].ToString();
intTxt.Text = total[3].ToString();
wisTxt.Text = total[4].ToString();
chaTxt.Text = total[5].ToString();
The thing is, if I add this messagebox
MessageBox.Show(i.ToString());
after
total[i] = die[0] + die[1] + die[2] + die[3] - smallest;
the numbers each get unique outputs, as intended.
I'm thinking it has something to do with threading, but figured I'd ask here before messing something up.
you are recreating the random number generator every time in the loop, create one before the loop:
Random rand = new Random();
for(int i = 0; i < total.Length; i++)
{
...
}
see also here and here, it explains why the numbers don't change
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 4 years ago.
I'm writing a Assignment for school (we are sepose to make one for the rest of the class) and I have run in to a problem. I'm having IndexOutOfRangeException errors when running the program and I can't figure out why I'm getting it.
Random rnd = new Random();
string strNumDice = tbxNumDice.Text;
int[] numDice = new int[int.Parse(strNumDice)];
int numSides = int.Parse(tbxNumSides.Text);
int trgNumber = int.Parse(tbxTarget.Text);
int sum = 0;
//int numTries = 0;
int var2 = 0;
if (int.Parse(strNumDice) * (numSides) >= trgNumber)
{
while (var2 != trgNumber)
{
tbxResult.AppendText("\n");
sum = 0;
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
tbxResult.AppendText(numDice[numberOfDice].ToString() + " ");
sum += numDice[numberOfDice];
//numTries++;
}
tbxResult.AppendText("\n");
tbxResult.AppendText("The new sum is" + sum.ToString());
var2 = sum;
}
}
If I decide to roll 6 d6's and wan't a target sum of 36 it will continue to do so until it gets to 36.
The mistake is here:
foreach (int numberOfDice in numDice)
{
numDice[numberOfDice] = rnd.Next(1, numSides+1);
This is how javascript does foreach loops: you get the indexes of your array. C# gives you the values of the actual elements, rather than the indexes. As you will be modifying actual array elements, you want a for loop, rather than a foreach loop, like this:
for(int i = 0; i<numDice.Length; i++)
{
numDice[i] = rnd.Next(1, numSides+1);
This question already has answers here:
2d Array in C# with random numbers
(2 answers)
Closed 4 years ago.
How do you print and save random values in array using Random.
So I need to have 10x10 table of rows containing random values from 0-9 but I seem to can't find a way how to get them printed!
int[,] mas = new int[9,9];
Random rand = new Random();
for (int i = 0; i <mas.Length; i++)
{
mas[i] = rand.Next(0,9);
Console.WriteLine(mas[i]);
for (int k = 0; k < mas.Length; k++)
{
mas[k] = rand.Next(0,9);
Console.WriteLine(mas[k]);
}
}
You have a small issue in your code: The array you create has two dimensions (int[9,9]). Therefore, whenever you want to read or write a cell, you need to provide two coordinates. You only set mas[i] or mas[k].
You should use max[i,k] instead in the inner loop. That way, every combination of coordinates will be tried out.
Unrelated: You mention you want a 10x10 grid of cells, but declare int[9,9]. While array indexing starts at 0, the size starts at 1. For example, if you create an array a = int[2], then it only contains entries at int[0] and int[1].
Similarly, the maximum parameter of the Random.Next(...) function is exclusive, so to get the value 9, you need to pass the maximum value 10.
If you want 2D array (i.e. you have two coordinates: lines - i and columns - j), nested loops is usual choice:
Random rand = new Random();
int[,] mas = new int[9, 9];
for (int i = 0; i < mas.GetLength(0); ++i)
for (int j = 0; j < mas.GetLength(1); ++j)
mas[i, j] = rand.Next(0, 10); // 10 will not be included, range [0..9]
Let's print the array:
for (int i = 0; i < mas.GetLength(0); ++i) {
for (int j = 0; j < mas.GetLength(1); ++j) {
Console.Write(mas[i, j]);
Console.Write(' '); // <- delimiter between columns
}
Console.WriteLine(); // <- delimiter between lines
}
Also, note that mas.length returns the overall length of the array, which will give you an IndexOutOfRangeException using your Code. Use mas.GetLength instead of mas.length
myArray.GetLength(0) -> Gets first dimension size
myArray.GetLength(1) -> Gets second dimension size
So your Code would look like this:
int[,] mas = new int[9, 9];
Random rand = new Random();
for (int i = 0; i < mas.GetLength(0); i++)
{
for (int k = 0; k < mas.GetLength(1); k++)
{
mas[i, k] = rand.Next(0, 9);
Console.Write(mas[i, k] + " ");
}
Console.WriteLine();
}
Probably like this
int[,] mas = new int[10, 10];
Random rand = new Random();
for (int i = 0; i < mas.GetLength(0); i++)
{
for (int k = 0; k < mas.GetLength(1); k++)
{
mas[i,k] = rand.Next(0, 9);
Console.Write(mas[i,k]);
}
Console.WriteLine("\n");
}
There are many things wrong with your code,
You dont know how indexing works - you want array of 10 times 10 but you create one with 9 times 9.
You need to specify both dimenstion when adding number to array.
Also,
Consolo.Writeline(string);
Will always write new line, something you dont want since you want to print 10 numbers, then new line with another then etc.
I would like to generate array of 10 elements with random number between (-10,10).
And scenario is array can contain positive number between (0,10) for odd positions
and contain negative number between(-10,0) for even position
For Example: 1,-2,3,-4,7,-1,3,-3,2,-9
And im totally stucked in generating -ve number at even places because im new in programming.
Any Help Is Appreciated,Thanx In Advance
Ok, i got your point. Try This Code
Random rand = new Random();
int[] arr = new int[10];
for(int i = 0; i < 10; i++)
{
if(i % 2 == 0)
arr[i] = rand.Next(1,10);
else
arr[i] = (rand.Next(1,10)) * -1;
}
for(int i = 0; i < 10; i++)
{
Console.WriteLine(arr[i]);
}
Sample Output
1
-9
9
-8
1
-4
2
-6
4
-9
Try this:
using System;
namespace ConsoleApp
{
class Program
{
static void Main (string[] args)
{
var random = new Random ();
var array = new int[10];
for (int i = 0; i < array.Length; i++)
{
bool isOdd = (i % 2) == 1; // check remainder
int randomNumber = random.Next (0, 11); // 0..10
if (isOdd) randomNumber = -randomNumber; // change sign
array[i] = randomNumber;
}
}
}
}
This is easier than all the posted answers so far. Here is a basic infinite loop from which to base your specific needs.
public IEnumerable<int> RandomAlternatingSequence()
{
var random = new Random();
int sign = -1;
while (true)
{
sign *= -1;
yield return sign * random.Next();
}
}
I realize that the post is 2 years old but this may help others who come looking.
This question already has answers here:
Best way to repeat a character in C#
(21 answers)
Closed 5 years ago.
Hi im trying to make it so I can generate a random number 1-35 so for example if the number is 25 it will write out in a string 25 equal signs. How can I do that?
Random r = new Random();
r.next(1, 35);
R's result = 25
string result = 25 equal signs
Class string has a constructor that can do the work for you.
Random r = new Random();
int number = r.next(1, 35);
string result = new string('=', number);
Note also that it should be r.Next() not r.next().
Random r = new Random();
int occurrences = r.Next(1, 35);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < occurrences; i++)
{
sb.Append('=');
}
string output = sb.ToString();
Console.WriteLine(output);
You need a loop to repeat adding = to your result.
Update your code to
Random r = new Random();
int total = r.next(1, 35);
string result = "";
for (int i = 0; i < total; i++)
{
result += "=";
}
This question already has answers here:
C# creating a list of random unique integers
(6 answers)
Closed 4 years ago.
I want to make an array of random numbers without any duplicate.
private void SetRandomQuestions()
{
var idS = from t in _db.QuestionsTables
where t.Cat_Id == _catId
select new
{ t.Question_Id };
// to get the questions Id from database table
foreach (var variable in idS)
{
array.Add(variable.Question_Id);
}
// generate a random numbers depends on the array list values
var random = new Random();
for (var i = 0; i < _randomQuestionId.Length; i++)
{
_randomNumber = random.Next(array.Count);
for (var j = 0; j < _randomQuestionId.Length; j++)
{
if (_randomQuestionId[j] != array[int.Parse(_randomNumber.ToString())])
{
_randomQuestionId[i] = array[int.Parse(_randomNumber.ToString())];
j = 5;
}
}
}
}
As you see here I have list array has values of questions id and further I have created another array to get 4 elements randomly from that array.
However, my question is how I can get the elements without any duplicate Ids I have tried many times but unfortunately I didn't success with that.
The simplest thing would be shuffling your question ids and then taking the first four.
Random rnd = new Random();
randomQuestionId = idS.OrderBy(_ => rnd.Next()).Take(4).ToArray();
Try this, this code will generate unique random numbers
int smallestNumber = 1;
int biggestNumber = 50;
//Determine the amount of random numbers
int amountOfRandomNumbers = 10;
//Create a list of numbers from which the routine
//shall choose the result numbers
var possibleNumbers = new List<int>();
for (int i = smallestNumber; i <= biggestNumber; i++)
possibleNumbers.Add(i);
var result = new List<int>();
//Initialize a random number generator
Random rand = new Random();
//For-loop which picks each round a unique random number
for (int i = 0; i < amountOfRandomNumbers; i++)
{
//Generate random number
int randomNumber = rand.Next(1, possibleNumbers.Count) - 1;
result.Add(possibleNumbers[randomNumber]);
//Remove the chosen result number from possible numbers list
possibleNumbers.RemoveAt(randomNumber);
}
//Now loop on result and print the output
var pickFour = array
.OrderBy(p => Guid.NewGuid())
.Take(4);