Reputation: 6170
I'm using a multidimensional array to create a "border". If it was printed, it would look something like this:
######
# #
# #
# #
######
The code I have so far can create the top, left, and bottom borders. At the moment I don't know how to create the border for the right hand side of it.
int[,] array = new int[10, 10];
//Create border around box
//Top
for (int i = 0; i < array.GetLength(0); i++)
{
array[0, i] = 1;
}
//Bottom
for (int i = 0; i < array.GetLength(0); i++)
{
array[array.GetLength(0) - 1, i] = 1;
}
//Left
for (int i = 0; i < array.GetLength(0); i++)
{
array[i, 0] = 1;
}
How do I go about creating the border on the right? Also, I think my code could be improved, I'm new to C#.
Thanks
Upvotes: 1
Views: 1293
Reputation: 110171
int x = 10;
int y = 10;
int[,] array = new int[x, y];
// iterate over the left coordinate
foreach(int i in Enumerable.Range(0, x))
{
array[i,0] = 1; //bottom
array[i,y-1] = 1; //top
}
// iterate over the right coordinate
foreach(int i in Enumerable.Range(0, y))
{
array[0,i] = 1; //left
array[x-1,i] = 1; //right
}
Upvotes: 0
Reputation: 13022
The right border is the reflection of the bottom border along the diagonal (top-left to bottom-right). So, take the bottom drawing code and invert the x, and y coordinates. It gives:
// Right
for (int i = 0; i < array.GetLength(0); i++)
{
array[i, array.GetLength(0) - 1] = 1;
}
Your code is correct. I would suggest just 2 improvements:
First, in C#, array dimensions is cannot be changed after the creation of the array and you know the size of your array: 10. So, let's replace all array.GetLength(0)
by a an int called arraySize
.
const int arraySize = 10;
int[,] array = new int[arraySize, arraySize];
//Create border around box
//Top
for (int i = 0; i < arraySize; i++)
{
array[0, i] = 1;
}
//Bottom
for (int i = 0; i < arraySize; i++)
{
array[arraySize - 1, i] = 1;
}
//Left
for (int i = 0; i < arraySize; i++)
{
array[i, 0] = 1;
}
// Right
for (int i = 0; i < arraySize; i++)
{
array[i, arraySize - 1] = 1;
}
Second improvements. You use multiple times the same loops. Let's merge them together.
const int arraySize = 10;
int[,] array = new int[arraySize, arraySize];
// Create border around box
for (int i = 0; i < arraySize; i++)
{
array[0, i] = 1; // Top
array[arraySize - 1, i] = 1; // Bottom
array[i, 0] = 1; // Left
array[i, arraySize - 1] = 1; // Right
}
Upvotes: 1
Reputation: 15968
Since all the for loops have the same bounds why not do it in one loop like this:
for (int i = 0; i < array.GetLength(0); i++)
{
//Top
array[0, i] = 1;
//Bottom
array[array.GetLength(0) - 1, i] = 1;
//Left
array[i, 0] = 1;
// Right
array[i, array.GetLength(0) - 1] = 1;
}
Upvotes: 1