user3328039
user3328039

Reputation: 79

How to add a row to 2D array

I have an array with 89395 rows and 100 columns.

float[][] a = Enumerable.Range(0, 89395).Select(i => new float[100]).ToArray();

I wanna get the index of last row from this array and add one row(lastindex+1) to array and insert 100 floats to the new row which are random. Also save the new index (number of new row) into the userid variable. I wrote the below code in C#.

public float random(int newitemid)
{
    a.Length = a.Length+1;
    int userid = a.Length;
    Random randomvalues = new Random();
    float randomnum;
    for (int counter = 0; counter < 100; counter++)
    {
        randomnum = randomvalues.Next(0, 1);
        a[counter] = randomnum;
    }
    return a;
}

Upvotes: 2

Views: 9335

Answers (1)

Matty
Matty

Reputation: 505

You could do this:

public float random(int newitemid)
{
    // Create a new array with a bigger length and give it the old arrays values
    float[][] b = new float[a.Length + 1][];
    for (int i = 0; i < a.Length; i++)
        b[i] = a[i];
    a = b;

    // Add random values to the last entry
    int userid = a.Length - 1;
    Random randomvalues = new Random();
    float randomnum;
    a[userid] = new float[100];
    for (int counter = 0; counter < 100; counter++)
    {
        randomnum = (float)randomvalues.NextDouble(); // This creates a random value between 0 and 1
        a[userid][counter] = randomnum;
    }
    return a;
}

However, if you use this method more than once or twice, you really should consider using a list, that's alot more efficient.

So use List<float[]> a instead.

P.S. If you don't use the parameter newitemid, then it's better to remove it from the function I guess.

Edit: I updated the randomnum to actually generate random numbers instead of 0's

Upvotes: 1

Related Questions