I am trying to initialize 2-dimensional array of integer values with -1. When I create a new array, it is automatically filled with 0. I know I can do it with 2 for cycles, but I imagine there should be some way of doing this while the array is being build (so I don't have to go through it two times), so that instead of 0, provided value would be inserted. Is it possible? If not during the initial building of the array, is there some other time or code saving way, or am I stuck with 2 for cycles?
-
3How large are these arrays?Reed Copsey– Reed Copsey2013-02-26 00:37:10 +00:00Commented Feb 26, 2013 at 0:37
-
1Array size is based on the input of the function that creates it, I forgot to mention that. Direct initialization is out of question.kovike– kovike2013-02-26 00:40:00 +00:00Commented Feb 26, 2013 at 0:40
3 Answers
Try something like this: int[,] array2D = new int[,] { { -1 }, { -1 }, { -1 }, { -1} };
or with dimension int[,] array2D = new int[4,2] { { -1,-1 }, { -1,-1 }, { -1,-1 }, {-1,-1} };
3 Comments
With a multidimensional array, the loops are most likely the best approach, unless the array is small enough to initialize directly in code.
If you're using a jagged array, you could initialize the first sub-array, then use Array.Copy to copy these values into each other sub-array. This will still require one iteration through the first sub array, and one loop through N-1 outer arrays, but the copy operation will be faster than the loops.
1 Comment
In Python, this kind of 2D array initialization is wrong:
mat = [[0] * 5] * 5 # wrong
mat = [[0] * 5] for _ in range(5)] # correct
because you are copying the reference of the inner array multiple times, and changing one of them will eventually change all.
mat[0][0] = 1
print(mat)
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
# 1 0 0 0 0
In C#, we have the similar issue.
var mat = Enumerable.Repeat(Enumerable.Repeat(0, 5).ToArray(), 5).ToArray();
Since array is a reference type, the outside Repeat() are actually copying the reference of the inner array.
Then if you do have the need to create and initialize multidimensional arrays without using for loops, then maybe a custom helper class will help:
static class HelperFunctions
{
public static T[][] Repeat<T>(this T[] arr, int count)
{
var res = new T[count][];
for (int i = 0; i < count; i++)
{
//arr.CopyTo(res[i], 0);
res[i] = (T[])arr.Clone();
}
return res;
}
}
Then if you want to use it:
using static HelperFunctions;
var mat = Enumerable.Repeat(0, 5).ToArray().Repeat(5);
This will do.