How to fix IndexOutOfRangeException [duplicate] - c#

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

Related

C# Define Variables using Loop [duplicate]

This question already has answers here:
Create dynamic variable name
(5 answers)
Closed last year.
Ok this might be a weird question and I don't really know how to phrase it so I just show you an example:
int i = 0;
int k = 100;
while (i <5) {
***response+i*** = k + i;
i++;
}
I want to declare multiple Variables (response1, response2, respons3 ...) using a loop, so that in the end the result is:
response1 = 101
response2 = 102
response3 = 103
etc.
I am still a beginner at C# and programming in general, so I don't know if that is even possible how I imagine it, hope you can help me, thanks.
First, You can not define a variable by using two variable. That is not how compiler work.
Maybe you should try to create a Array or List to store the value
like this example
int i = 0;
int k = 100;
int[] response = new int[100];
while (i < 5)
{
response[i] = k + i;
i++
}
if you don't know the array size you want , try to do with List
List<int> response = new List<int>();
int i = 0;
int k = 100;
while (i < 5)
{
response.Add(i + k);
i++;
}
You should really use an array for these values, it's not really possible to use dynamic variable names.
I would also use a for loop where you need the index variable rather than having to manually update it in the while loop.
var results = int[5];
int k = 100;
for (var i = 0; i < results.Length; i++)
results[i] = k + i;

C# System.IndexOutOfRangeException or cant convert to Long [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm kinda of having this error:
"System.IndexOutOfRangeException: Index was out of the Array"
When I change int=1 to long=1 it says it can't convert long to int.
I'm trying to save all output of N into the Array and show at the end what is saved into arrays.
static void Main(string[] args)
{
int a = 0;
a = Convert.ToInt64(Console.ReadLine());
int[] array = new int[a];
if (a == 0)
{
Console.WriteLine("Falsche eingabe.");
}
else
{
long n = 1;
for (int i = 1; i <= array.Length; i++)
{
n *= i;
array[i] = n;
Console.WriteLine("N: " + i + " Fakultät von N: " + array[i]);
}
}
Console.ReadKey();
}
Indexes of arrays begin from 0 not from one. Therefore in your for loop, i <= array.Length, when i is equal to the length you enter and try array[array.Length] which throws the exception. Change to:
for (int i = 0; i < array.Length; i++)
Reason indexes are zero based is that the language is based on C where an array is a pointer to the location that was allocated for the array:
int *arrayPointer;
And then to go through the array one needs to go to arrayPointer + sizeof(int)*i. So for the first position of the array i should start from zero
In addition this line doesn't compile:
a = Convert.ToInt64(Console.ReadLine());
a is of type int while you are converting to long. Use ToInt32

Generate array of random number without duplicates [duplicate]

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

For Loops Not Always Updating C# [duplicate]

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

Use rand5(), to generate rand7() (with the same probability) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Expand a random range from 1–5 to 1–7
I have seen the question in here: Link
The solution the author provided didn't seem to generate the same probability.
For example, the number 4, out of 10k calls for the function, was returned 1-2 times (when the other numbers, like 2, were returned about 2k times each).
Maybe I understood wrong, or I wrote the algorithm wrong, but here:
static int rand5()
{
return new Random().Next(1, 6);
}
static int rand7()
{
while (true)
{
int num = 5 * (rand5() - 1) + rand5();
if (num < 22) return ((num % 7) + 1);
}
}
static void Main(string[] args)
{
int limit = 10000;
int[] scores = new int[7];
for (int i = 0; i < limit; i++)
{
scores[rand7() - 1]++;
}
foreach (int n in scores)
{
Console.Write(n + " ");
}
Console.WriteLine();
}
Thanks in advance.
You are not generating random numbers in Rand5.
Do it like this:
static Random rand = new Random()
static int rand5()
{
return rand.Next(1, 6);
}

Categories

Resources