Reputation: 357
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[,]
Upvotes: 0
Views: 187
Reputation: 186833
Well, you should return 2d array: int[,]
:
public static int[,] SquarePatch(int n) {
// Do not forget to validate input values (n) in public methods
if (n < 0)
throw new ArgumentOutOfRange(nameof(n));
// We want to return 2d array, here it is
int[,] result = new int[n, n];
// All we should do now is to loop over 2d array and fill it with items
for (int r = 0; r < result.GetLength(0); ++r)
for (int c = 0; c < result.GetLength(1); ++c)
result[r, c] = n;
return result;
}
You can change your challenge and return jagged array int[][]
(array of arrays):
public static int[][] SquarePatch(int n) {
// Do not forget to validate input values (n) in public methods
if (n < 0)
throw new ArgumentOutOfRange(nameof(n));
// now we want to return array of size n (lines) of arrays:
int[][] result = new int[n][];
// We loop over lines
for (int r = 0; r < result.Length; ++r) {
// We create line after line
int[] line = new int[n];
// assign each line to result
result[r] = line;
// and fill each line with required items
for (int c = 0; c < line.Length; ++c)
line[c] = n;
}
return result;
}
Upvotes: 1
Reputation: 23867
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.
Upvotes: 1