-1

I am currently trying to make a Perlin noise generator in C# and I need a massive 2D array to use.

This is my current solution, but for a bigger array, I could not do this.

int[,] noise = new int[8, 8]{
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0},
  {0,0,0,0,0,0,0,0}
};
Rand Random
  • 7,300
  • 10
  • 40
  • 88
mr dr
  • 1
  • 1
  • 1
  • 1
    Loop them and fill them. – Rand Random Jan 25 '19 at 05:40
  • You can refer to this answer. https://stackoverflow.com/a/9894155/3890171 – Redice Jan 25 '19 at 05:46
  • Why do you need to fill array with zeros when it is default already? or you are asking about some other values ? – Alexei Levenkov Jan 25 '19 at 05:57
  • To extend on Alexei's comment - in C# array will be initialized with default(T), which for numeric types will be 0, for classes null, etc. – johannes.colmsee Jan 25 '19 at 06:01
  • When you finish, I'm assuming that your array won't be entirely zeroes (as others have pointed out, you get that for free). If your array is truly massive, is nearly all zeroes (but has some non-zero elements), consider writing a *sparse array* class, where you only keep track of the non-zero elements. The easiest implementation would store the non-zero elements in a `Dictionary` with a key typed as a value-tuple of two ints (x and y) and the value matching the array type. I think you can write a 2D indexed property, so you can make it look like a 2D array – Flydog57 Jan 25 '19 at 06:16

1 Answers1

2

You can write a function to fill the array. array.GetLength(dimesion number) returns the size of that dimension for multi-dimensional arrays in C#. The dimension number is 0 for rows and 1 for columns for 2D. So write a function like this:

  public static void fill2DArray(int[,] arr){
    int numRows = arr.GetLength(0);
    int numCols = arr.GetLength(1);

    for(int i = 0; i < numRows; ++i){
        for(int j = 0; j < numCols; ++j){
            arr[i,j] = 0;
        }
    }
}

Try calling the function like fill2DArray(myArray);. You can also use the Random within to fill with random data.

Dblaze47
  • 868
  • 5
  • 17
  • Code does not look valid. Please make sure to check source (like https://stackoverflow.com/questions/9894084/2d-array-set-all-values-to-specific-value/9894155#9894155) before copy-paste. – Alexei Levenkov Jan 25 '19 at 06:24
  • I typed [i][j] instead of [i,j] by mistake. I have fixed that and it is working and I have tried out filling an array passing values in the parameter. – Dblaze47 Jan 25 '19 at 11:01