I need to create an array for which I do not know the size in advance. I used the following, but it gives an index out of bounds error in my for -loop.
string[] arr = s.Split('\n');
int[] indices = new int[arr.Length];
string[][] new_arr = new string[arr.Length][];
for (int i = 0; i < arr.Length; i++)
{
if (arr[i].StartsWith("21"))
{
indices[i] = i;
}
}
indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i];
} //first n elements
The error is in the second for-loop. It says
Object reference not set to an instance of an object.
But I did instantiate the string at the beginning?
You just need to initialize each of the arrays within the jagged array:
indices = indices.Where(val => val != 0).ToArray(); //contains indices of records beginning with 21
// create second-level array
new_arr[0] = new string[indices.Length] ;
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i]; // why 0 here?
}
For a 2 dimensional array, you will have to specify the size of the first dimension. As I see your code, it is using what is called the jagged array (array containing array as elements) and not a pure 2 dimensional array.
var array1 = new int[2,10]; // this is a 2 dimensional array
var array2 = new int[2][]; // this is an array of 2 elements where each element is an `int[]`
As you notice, we don't need to specify the size of the inside element int[]
Now you understand the jagged array, you can see that you are not initializing the inside element, but simply accessing it - and since it is null by default, you hit the exception.
for (int i = 0; i < indices.Length - 1; i++)
{
new_arr[0][i] = arr[i];
} //first n elements
In the code above, you should have new_arr[i][0] = arr[i] and also before that line you need to do new_arr[i] = new int[x] where x is teh size that you want for the inside array.
Related
I have got 25 elements in my txt file. My code calculates their scores according to answer key. Then i would like to sort them without using sort.Array etc. I made it and a assigned them another array which is name is result. Now i would like to write the elements number according to order of result array
. For example the element 101' score 78. The element 105' s score is 25.
The result array sort them: 78-25
i would like to sort them : 101-105
my code is:
//arranging results according to their values
int temp = 0;
int[] elm = new int[result.Length];
for (int i = 0; i <= result.Length-1 ; i++)
{
for (int j = i+1 ; j < result.Length; j++)
{
if (result[i] < result[j])
{
temp = result[i];
result[i] = result[j];
result[j] = temp;
}
elm[j] = Convert.ToInt16(row[i,0]);
}
;
}
Let's say I want to write a value in a int[], but I don't yet know what will be the length of that array.
Currently, I just run whatever algorithm I'm using once to get the length of the array, then I instanciate the array and finally run the same algorithm modifying the elements of the array.
Here's a code example:
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
length++;
}
}
array = new int[length];
for (int i = 0; i < input.length; i++)
{
if (i == condition)
{
array[i] = whatever;
}
}
Just use lists
List<string> list = new List<string>();
When adding elements just do:
list.Add("Hello, world!");
You do not need to specify length for a list and you can add as many elements as you like
https://www.c-sharpcorner.com/article/c-sharp-list/
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-6.0
I'm trying to create an array with the following structure
D
C C
B B B
A A A A
Which will be N x N but split diagonally. Initially, all I know is the bottom row essentially just:
string[,] table = new string[n,];
How can I build on this structure so that when I get to the next row I can declare how many elements it has? Would it be something along the lines of:
for(int i = 0; i <= n; i++) {
table[i] = new string[--n]
}
The [,] syntax creates multidimensional arrays, not jagged arrays. For the latter, you would need to do this:
int n = 4;
string[][] table = new string[n][];
for (int i = 0; i < n; i++)
table[i] = new string[n-i];
Btw. you really don’t want to decrement n while looping in a loop with the condition i < n (or i <= n).
I'm trying to build a multi-dimensional array to store integer arrays.
Array[] TestArray = new Array[2];
for(int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new int[5];
}
How do I go about accessing the newly created members of the Array? I am not sure how to access the newly created arrays in the array although I can see that they're properly created and stored when debugging in Visual Studio.
If you want an array of integer arrays, then you should declare it as such:
int[][] testArray = new int[2][];
for(int i = 0; i < testArray.Length; i++)
{
testArray[i] = new int[5];
}
Arrays of arrays are called Jagged Arrays (in contrast to Multidimensional Arrays).
Here is how to access fourth item in the second array:
int value = ((int[]) TestArray.GetValue(1))[3];
Although you would have much less trouble working with jagged arrays:
int[][] TestArray = new int[2][];
for (int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new int[5];
}
or multidimensional arrays:
int[,] TestArray = new int[2,5];
Cast the TestArray element as an int[].
Array[] TestArray = new Array[2];
for(int i = 0; i < TestArray.Length; i++)
{
TestArray[i] = new [] { 2,3 };
}
var firstIndexOfFirstArray = ((int[])TestArray[0])[0];
T[][] is the syntax you are looking for.
int[][] test = new int[2][]; //Declaring the array of arrays.
for (int i = 0; i < test.Length; i++)
{
test[i] = new int[5]; //Instantiating a sub-arrays.
for (int x = 0; x < test[i].Length; x++)
test[i][x] = x + i; //Filling a sub-arrays.
}
foreach (var array in test) //iterating over the array of arrays.
Console.WriteLine("Array: " + string.Join(", ", array)); //using a sub-array
Console.ReadLine();
For more info: http://msdn.microsoft.com/en-us/library/2s05feca.aspx
If looking for integer array, try
int[][] testArray
I have a 2-dimensional array of objects, which I initialize using the traditional loop:
PairDS[,] tempPb1 = new PairDS[LoopCounterMaxValue+1, LoopCounterMaxValue+1];
for (int i = 0; i <= LoopCounterMaxValue; i++)
for (int j = 0; j <= LoopCounterMaxValue; j++)
tempPb1[i, j] = new PairDS();
Is there any better way to do this using Enumerable or something?
I thought Initialize could do it, but it only works with value types.
int N = 10;
PairDS[,] temp = new PairDS[N + 1, N + 1];
temp.Initialize();
What I recommend you do is use a jagged array.
class PairDS { public PairDS(int row, int col) { } }
static void Main(string[] args)
{
int N = 10;
PairDS[][] temp = Enumerable.Range(0, N + 1).Select(
(row) => Enumerable.Range(0, N + 1).Select(
(col) => new PairDS(row, col)).ToArray()).ToArray();
}
I don't believe you can represent a multi-dimensional array as an Enumerable or List, directly because it (the CLR) has no way of knowing how you intend to index the array.
If you did work it out row by row, it'd actually be worse (ie slower) then simply looping through the array as you're doing and initializing each cell.
There's no way to directly initialize a 2D array with the Enumerable types and as some users have pointed out there's nothing directly wrong with what you're doing. If you're just looking to simplify the loop though this might be what you're looking for;
const int length = LoopCounterMaxValue + 1;
PairDS[,] tempPb1 = new PairDS[length, lenth];
for (var i = 0; i < length * length; i++) {
var column = i % length;
var row = (i - column) / length;
tempPb1[row, column] = new PairDS();
}