0

I've got this program where I'm creating a character array that's filed with a given character, and I was wondering if there is a faster way to do so than the nested for loops that I've been using, like the numpy.zeros command in python. Like for an array arr,

char[,] arr = new char array[3, 4]

Is there a faster way to fill it than:

        for (int i=0; i<3; i++)
        {
            for (int j=0; j<4; j++)
            {
                arr[i, k] = 'a';
            }
        }
  • Since you reference `numpy.zeros`, do you mean faster in terms of execution? Or less code? – Stanislas Feb 04 '21 at 17:12
  • Does this answer your question? [How to populate/instantiate a C# array with a single value?](https://stackoverflow.com/questions/1014005/how-to-populate-instantiate-a-c-sharp-array-with-a-single-value) – Stanislas Feb 04 '21 at 17:15
  • @Stanislas Yeah i meant less code, could've framed it better, my bad, though its answered now – Outofnameideas Feb 05 '21 at 11:48

2 Answers2

0

The below will create a 5 by 5 char[][] with a single value, J in this case.

char[][] result = Enumerable.Repeat(Enumerable.Repeat('J', 5).ToArray(),5).ToArray();
Ben
  • 757
  • 4
  • 14
0

If your array is just 3 by 4 and you really need something faster than a nested loop this would do the trick.

arr = new char[3, 4] { { 'a', 'a', 'a', 'a' }, { 'a', 'a', 'a', 'a' }, { 'a', 'a', 'a', 'a' }};