I have a problem extracting the columns length in jagged array like this:
How can I get the length of the 2nd (with index 1 and length 8) or the 5th (index 4 and length 4) column for example? Same with the rows. I need length of a specified row.
I have a problem extracting the columns length in jagged array like this:
How can I get the length of the 2nd (with index 1 and length 8) or the 5th (index 4 and length 4) column for example? Same with the rows. I need length of a specified row.
The method getColumnLength just goes through each row and checks if the row is long enough for the column to be in it. If it is then add it to the count of rows that have that column.
public class Program {
public static void Main(string[] args) {
int[][] jaggedArray = {
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
Console.WriteLine(getColumnLength(jaggedArray, 4));
Console.WriteLine("Press any key to continue. . .");
Console.ReadKey();
}
private static int getColumnLength(int[][] jaggedArray, int columnIndex) {
int count = 0;
foreach (int[] row in jaggedArray) {
if (columnIndex < row.Length) count++;
}
return count;
}
}
You should be able to get the row length fairly easily as that is simply going to be the length of an individual array in your array of arrays. For example: arrays[3].length
would be 8.
Columns is different because we need information about every array. We can iterate through, counting the number of arrays whose lengths are greater than the column number you're looking for.
public static int getColumnLength(int[][] arrays, int columnNumber) {
int count = 0;
for(int i = 0; i < arrays.length; i++) {
if (arrays[1].length > columnNumber) {
count++;
}
}
}
Use LINQ!
public static int GetColumnSize<T>(this T[][] array, int columnNumber) =>
array
.Where(subArray => subArray.Length > columnNumber)
.Count();
public static int GetRowSize<T>(this T[][] array, int rowNumber) =>
(array.Length <= rowNumber)
? array[rowNumber].Length
: 0;
My task is to overflow the column for example if I am in position [2][2] ( number 9 ) and when the user types "go up with 4 steps" I need to enter from the other side of column and go to the element [4][2] ( number 15 ) on the image.
I have the following method for overflowing:
static int index(int i, int n)
{
return i % n < 0 ? n + (i % n) : i % n;
}
where i is the current position and n is the length of column/row