nested loop with array c# [duplicate] - c#

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I have the following array:
public int[] ID = {0,1,2,3,4};
I´m calling the following method, which contains an get-method in an framework:
int[] marker = this.m_TuioManager.getID(this.ID);
Get-Method in the framwork class:
public int[] getID(int[] wert)
{
int number= 4;
for (int i = 0; i<=number; i++)
{
for (int j = 0; j<=number; j++)
{
wert[i] = wert[j];
}
}
return wert;
}
The exception is:
Array index out of range
which I don´t understand. Cauze my array has 5 numbers from 0 to 4. And in the for loop I´m iterating until 4.
What I want later, is to compare the values in the array like wert[0] = 0, wert[1] = 1 and so on(until 4),with an other variable.

If you want to avoid "Array index out of bounds" errors, don't write code that assumes arrays always have X number of elements. Either check the .Length of the array before you attempt to access 4 elements of it, or write a loop that runs to the array.Length rather than always running to a fixed 4 elements
if(array.Length < 4)
throw new Exception("min array length is 4, you passed " + array.Length);
Or
for(int i = 0; i < array.Length; i++)
Or
foreach(int i in array)
If you can get any of these lines of code to crash with an AIOOB exception, inform Microsoft

Related

How to solve Cannot convert type 'int' to 'int[]' error? [duplicate]

This question already has answers here:
Iterate Multi-Dimensional Array with Nested Foreach Statement
(12 answers)
Closed 2 years ago.
I'm starting my own question because I can't find anything directly related to c# and the solution I am using is different approach.
The question is described as follows
In a given grid, each cell can have one of three values:
the value 0 representing an empty cell;
the value 1 representing a fresh orange;
the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange.
If this is impossible, return -1 instead.
Example 1:
Input: [[2,1,1],[1,1,0],[0,1,1]]
Output: 4
Example 2:
Input: [[2,1,1],[0,1,1],[1,0,1]]
Output: -1
Explanation: The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
Example 3:
Input: [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.
Note:
1 <= grid.length <= 10
1 <= grid[0].length <= 10
grid[i][j] is only 0, 1, or 2.
I currently have the following as my code:
public class Solution {
public int OrangesRotting(int[][] grid) {
var rows = grid.Length;
var cols = grid[0].Length;
HashSet<string> fresh = new HashSet<string>();
HashSet<string> rotten = new HashSet<string>();
for(var i = 0; i < rows; i++){
for(var j = 0; j < cols; j++){
var current = grid[i][j];
if(current == 1){
fresh.Add(""+i+j);
} else if (current == 2){
rotten.Add(""+i+j);
}
}
}
int minutes = 0;
int[,] directions = {{0,1},{1,0},{-1,0},{0,-1}};
while(fresh.Count > 0){
HashSet<string> infected = new HashSet<string>();
foreach(string s in rotten){
int i = s[0] - '0';
int j = s[1] - '0';
foreach(int[] direction in directions){
int nextI = i + direction[0];
int nextJ = j + direction[1];
if(fresh.Contains(""+nextI+nextJ)){
fresh.Remove(""+nextI+nextJ);
infected.Add(""+nextI+nextJ);
}
}
}
if(infected.Count == 0) return -1;
minutes++;
}
return minutes;
}
}
The issue I am having is I get the following compile error:
Line 29: Char 17: error CS0030: Cannot convert type 'int' to 'int[]' (in Solution.cs)
The array declaration int[,] directions defines a multidimensional array, which, strangely enough, is not an IEnumerable in C#. This means quite a few items that a "normal" array supports aren't available; one of them is a foreach iteration through the top-level array, which would make intuitive sense to write. Instead, what you're iterating through is a single-dimension representation of your multidimensional array - not what you want.
You can do one of two things: either use a jagged array instead - int[][] directions - or switch to a nested for loop instead, accessing each element of the array in the inner loop.

string of integers to int[] array C# [duplicate]

This question already has answers here:
Convert char to int in C#
(20 answers)
Closed 4 years ago.
This question is different as it tackles the issue of converting a char to an int when adding to an integer array.
The following piece of code, I am trying to implement a string of integers into a int[] array in C#.
My desired output is an array of:
12345678910
This is my code, however, the output of this is not what I desire:
string numbers = "12345678910";
int[] array = new int[numbers.Length];
for (int i = 1; i <= numbers.Length; i++)
{
array[i - 1] = numbers[i-1];
}
foreach(var y in array)
{
Console.Write(y);
}
Output of given code:
4950515253545556574948
Can somebode tell me why I am getting this output, and what I can do to fix this? Thank you!
Edit: Changed my code and it works using this:
for (int i = 0; i < numbers.Length; i++)
{
array[i] = int.Parse(numbers[i].ToString());
}
First of all, I don't think you'll be able to distinguish a two digit number using this method.
I refer to this part of your code: string numbers = "12345678910";
Iterate through your string characters and parse to Int (if that's what's required) (credit) (credit)
foreach (char character in yourString)
{
int x = (int)Char.GetNumericValue(character);
//code to add to your array of ints
}

Index out of range in for loop [duplicate]

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

Index was outside the bounds of the array error (C#) [duplicate]

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.

C# Get index values of max value in 2D integer array [duplicate]

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.

Categories