This question already has answers here:
Finding position of an element in a two-dimensional array?
(2 answers)
Closed 9 years ago.
Is there a slicker way? After populating the array with random numbers (and where the user determines the size of the 2D array) I got the max like this:
int largest = array.Cast<int>().Max();
Now to get the index values, the only way I could think was to do this:
for (int i = 0; i < rowsize); i++) {
for (int j = 0; j < columnsize); j++) {
if (largest == array[i, j])
Console.WriteLine("The index values of the largest value are {0} and {1}", i, j);
}
}
I was thinking there was a way to use the IndexOf method, couldn't find it. And I could be wrong, but a foreach loop doesn't seem to support index values.
There is a chance for duplicated max values in your current situation. You could probably save yourself half a millisecond saving the message to be displayed to a local variable and printing this after the loop in the form of message1\r\n\message2\r\n\r\nmessage3. However if you're only interested in the first occurance breaking from the loop might be worth considering.
Either way, you're basically fine.
Related
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 8 months ago.
got datagridview with 3 data, I want to get the first cells data on each rows, when I use this kind of code
string[] DataGridViewArray = { };
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
DataGridViewArray[i] = DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
}
textBox1.Text = DataGridViewArray.ToString();
why it keep said 'Index was outside the bounds of the array.'
Array is fixed size and its size is determined when declaring it (eg. in your first line of code) .
However, you gave it no single element nor set its size with expected number of items its going to hold - which in your case should be DataGridView1.Rows.Count.
string[] DataGridViewArray = { };
Instead, if you replace that (line #1 code) as follows, it should work:
string[] DataGridViewArray = new string[DataGridView1.Rows.Count];
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
DataGridViewArray[i] =
DataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
}
textBox1.Text = DataGridViewArray.ToString();
I don't have DataGridView1 but I did something similar just to show you the reason why you are getting out of index error and how to fix it.
Clostly look at the length of the array in a way you defined it vs when array length is provided when declaring it.
It's because you didn't properly instantiate your array so any iteration will be out of bounds.
This question already has answers here:
Randomize a List<T>
(28 answers)
Closed 5 years ago.
I want to fill a small array with unique values from a bigger array. How do I check the uniqueness?
Here's what I have:
int[] numbers45 = new int[45];
for (int i = 0; i <= 44; i++) // I create a big array
{
numbers45[i] = i + 1;
}
Random r = new Random();
int[] draw5 = new int[5]; //new small array
Console.WriteLine("The 5 draws are:");
for (int i = 1; i <= 4; i++)
{
draw5[i] = numbers45[r.Next(numbers45.Length)]; //I fill the small array with values from the big one. BUT the values might not be unique.
Console.WriteLine(draw5[i]);
}
There are multiple ways to do what you are asking.
First off, though, I would recommend to use one of the classes which wraps the array type and adds some extra functionality you could use (in this case a List would probably be a perfect structure to use)!
One way to handle this is to check if the value is already in the draw5 array. This can be done with (for example) the List<T>.Contains(T) function, and if it exists, try another.
Personally though, I would probably have randomized the first array with the OrderBy linq method and just return a random number, like:
numbers45.OrderBy(o => random.Next());
That way the numbers are already random and unique when it is supposed to be added to the second list.
And a side note: Remember that arrays indexes starts on index 0. In your second loop, you start at 1 and go to 4, that is, you wont set a value to the first index.
You could just run for (int i=0;i<5;i++) to get it right.
Inspired by Jite's answer, I changed to use Guid to randomize the numbers
var randomized = numbers45.OrderBy(o => Guid.NewGuid().ToString());
Then you could take the draws by:
var draws = randomized.Take(5).ToArray;
HashSet<int> hs = new HashSet<int>();
int next = random.next(45);
while(hs.Length <=5)
{
if(!hs.Contains(array[next]))
hs.Add(array[next]);
next = random next(45);
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
What is an "index out of range" exception, and how do I fix it? [duplicate]
(1 answer)
Closed 6 years ago.
So I am working on a game, aside from a game engine, and I have a for loop to detect collisions with all objects in a list of Panels
Here is the code:
for (int x = 1; x <= 2; x++)
{
if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
{
MessageBox.Show("COLLIDING");
}
}
Currently there are only two objects added to the list called walls
And everytime I go to run it tells me Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index I don't know what to do, am I setting up the if statement wrong?
I just tried taking it out of the for loop and replaced x with 0, and when I touched that object it said I was colliding, so I know I didn't set up the if statement wrong.
As you may or may not know, arrays start at 0 in the index, so your array should be like so.
for (int x = 0; x < 2; x++)
{
if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
{
MessageBox.Show("COLLIDING");
}
}
If there are 2 objects in walls the loop needs not go to x = 2
for (int x = 0; x < 2; x++)
{
if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
{
MessageBox.Show("COLLIDING");
}
}
As Arrays start at index 0
You have two elements in the walls[] array means they ware located in walls[0] and walls[1]( Since .Net arrays are following 0 based indexing) and hence walls[2] is out of bound; So you should start the loop with 0 to get the first element and loop up to 2. But i strongly recommend you to use length of walls instead of 2
for (int x = 0; x < walls.Length; x++)
{
if (player.obj.Bounds.IntersectsWith(walls[x].Bounds))
{
MessageBox.Show("COLLIDING");
}
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 7 years ago.
I have the following piece of code getting values from a Listbox. I've three teachers selected. when 'i' value reaches 3 it shows'Index was outside the bounds of array' error
string selectedTeachers = Request["SelectedTeachersList"];
int[] teachers_ID = Array.ConvertAll(selectedTeachers.Split(','), int.Parse);
for (int i = 0; i <= teachers_ID.Length; i++)
{
int Id = teachers_ID[i];
}
Arrays are zero based index, the first element in array will have zero index and last will have one less then size of array so it must be one less then the length of arry.
for (int i = 0; i < teachers_ID.Length; i++)
C# arrays are zero indexed; that is, the array indexes start at zero.
Read more about the arrays in MSDN Arrays Tutorial
You should do
for (int i = 0; i < teachers_ID.Length; i++)
(smaller to and smaller-or-equal operator)
If an array has 10 elements, you access them from index 0 to 9. Therefore, the for clause should exit, when i == 10. In your code, i==10 is still executed and then you obviously get an exception.
Use foreach here which is simple to use
foreach(int i in teachers_ID)
int Id = i;
You need not worry about the number of elements in the array in this case.
You got 'Index was outside the bounds of array' error because
C# arrays are zero indexed.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a list<>, filled with objects of my class. That one is working fine.
Now I want to load the last 10 elements to a new list<>, which is sorted upside-down. So the last Element will be the first of the new List<> and the 10th will be the last one in the new List<>.
Usually this shouldn't be such a hard task but I don't know... it iterates on the right way and should work in my opinion.
Both Lists<> are Lists<lastChanges>. lastChange is my class.
Here's what I got now:
// x represents the amount of elements for the new List<>
int x = 10;
// elems is the old list. if it contains less than 10 elements,
// x should be the amount instead of 10
if (elems.Count < 10)
{
x = elems.Count;
}
// The start-index is made by elems.Count -> 10 Items -> the 10th item
// would get the index '9'
// as long as i is greater than the amount of the large List<>
// minus the wanted amount for the new List<>
// the loop is going to repeat
for (int i = elems.Count-1; i > elems.Count - x; i--)
{
// lastChanges is my class which both Lists are filled with
lastChanges lastArt = elems[i];
if (lastArt != null)
{
items.Add(lastArt);
}
}
What am I missing? I really do not think I'm still a beginner (of course much to improve) but I can't find an error here...
For example:
The elems-List does contain 2 Elements,
then x would be equal 2.
The for-loop would start:
for(int i=1;i>0;i--)
so the loop would run twice.
In the first run there would be 'lastArt' set equal to the second object of 'elems' and than be added to 'items,
in the second run, the first item would be added to 'items'.
So, both items are added to 'items', everything is fine.
But why do I keep getting errors?
Both Objects are definetely != null...
Thank you!
edit:
I always get a 'NullReferenceException' in this line:
items.Add(lastArt);
Both Objects are definetely != null, so in my opinion it has to be an error in my iteration.
try to use LINQ
var result = data.Skip(data.Count - 10).Take(10);
List<SomeType> list = new List<SomeType>(result.Reverse());
It's easier to make your loop count up.
Rather than trying to keep track of i counting back from the last element, start with 1 and count up.
int numElements = 10; // or however you want from the end
for (int i = 1; i <= numElements && i <= elems.Count; i++)
lastItems.Add(elems[elems.Count - i]);
It's even easier to use LINQ.
List<MyClass> lastElements = elems.Reverse().Take(10).ToList();