Search code examples
c#multidimensional-arrayjagged-arrays

Jagged array of multidimensionnal array int types


I'm now learning C# and making a couple of challenges, i managed to pass easily most of them but sometimes there are things i don't understand (i'm a python dev basically)...

Create a function that takes an integer and outputs an n x n square solely consisting of the integer n.

E.G : SquarePatch(3) ➞ [
  [3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]
]

So i went trough docs about multidimentionnal arrays, jagged arrays.But i get an error (kind of errors i get the most while learning c#, i never had that kind of problems in python. It's about TYPES convertion !) I mean i often have problems of types.

So here's my code :

public class Challenge 
    {
        public static int[,] SquarePatch(int n) 
        {
        int[ ][,] jaggedArray = new int[n][,];
        for (int i=0;i<n;i++)
        {
            for(int j=0;j<n;j++)
            {
                for(int k=0;k<n;k++)
                    {
                        return jaggedArray[i][j, k]=n;
                    }
            }
        }
        }
}

What is actually very boring is that in that kind of challenges i don't know how to make equivalent to python "print tests" ! So i don't even know what's going on till the end...

And i get this error :

Cannot implicitly convert type int to int[,]

Solution

  • n as in the error message, cannot be converted to int[,]. It is an int. You don't need a jagged array but simply an array of n by n, hence arr[n,n].

    public static int[,] SquarePatch(int n, int v)
    {
        int[,] myArray = new int[n,n];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                myArray[i,j] = v;
            }
        }
        return myArray;
    }
    

    Here n is the size for row and cols and v is the value to initialize all members to.