axcelenator
axcelenator

Reputation: 1527

Resizing and initializing 2D array C#

I have a 2D array of type string which I want to modify and resize inside some loop. My main goal is to use minimum memory by creating a 2d array which will be modified every iteration of loop and the add a char to an appropriate cell in this array. Here is my code:

static void Main(string[] args)
    {
        int maxBound = 100;//length of freq array
        Random rnd1 = new Random();
        int numLoops = rnd1.Next(1000, 1200);//number of total elements in freq array
        int[] freq = new int[maxBound];//freq array
        string[,] _2dim = new string[maxBound, numLoops];//rows,columns
        Random rnd2 = new Random();

        for (int i = 0; i < numLoops; i++)
        {
            int s = rnd2.Next(maxBound);
            freq[s]++;
            //Here I try to add `*` to the _2dim array while resizing it to the appropriate size

        }
    } 

What is the main approach for the solution ? Thanks

Upvotes: 1

Views: 1981

Answers (2)

Matthias Herrmann
Matthias Herrmann

Reputation: 2790

You should use a list of type string nested in a List. Then you can modify this lists. For iterating through this you should use two for loops.

List<List<string>> l = new List<List<string>> { new List<string> { "a", "b" }, new List<string> { "1", "2" } };

Iteration example:

for(int i = 0; i < l.Count; i++)
        {
            for(int j = 0; j < l[i].Count; j++)
            {
                Console.WriteLine(l[i][j]);
            }
        }

Upvotes: 1

Gy&#246;rgy Kőszeg
Gy&#246;rgy Kőszeg

Reputation: 18023

Instead of a 2D array you might want to use a jagged one. Briefly, a 2D array is always an N x M matrix, which you cannot resize, whereas a jagged array is an array of arrays, where you can separately initialize every inner element by a different size (see the differences in details here)

int maxBound = 100;
Random rnd = new Random();
int numLoops = rnd.Next(1000, 1200);

string[][] jagged = new string[numLoops][];

for (int i = 0; i < numLoops; i++)
{
    int currLen = rnd.Next(maxBound);
    jagged[i] = new string[currLen];

    for (int j = 0; j < currLen; j++)
        jagged[i][j] = "*"; // do some initialization
}

Upvotes: 3

Related Questions