Related
I want to sort two-dimensional array. Instead of ordering for the first dimension I want to order the inner dimension.
For example if initial array is like this:
{{4, 1, 3},
{6, 5, 2},
{0, 9, 8}}
Then if we sort array by first row, result will be:
{{1, 3, 4},
{5, 2, 6},
{9, 8, 0}}
I managed doing this by transposing the array, ordering and transposing again. But is there a better way to do it?
Hmmmm this is a bit of an odd one and I actually misunderstood it at first. There are ways to do this but none of them that I can think of are really nice. Personally I think I would so something like
public class Matrix
{
private List<RowGroup> _groups;
public Matrix(List<List<int>> matrix)
{
//Removed for simplicity
}
public void SortMaxtrixByRow(int rowNumber)
{
this._groups.Sort((r1, r2) =>
{
return r1.Col[rowNumber].CompareTo(r2.Col[rowNumber]);
});
}
public class RowGroup
{
public List<int> Col;
public RowGroup(List<int> col)
{
Col = col;
}
}
}
This is doing something similar to your transposing. The main benefit would be that its an object so if you had to do multiple sorts on the same set it wouldn't need to re-transpose it over and over again.
Other than this you could copy the desired array and sort it then compare each value to the original to see how it moved and move the other rows accordingly but that is only assuming that you are using unique values in each row, writing your own sorting algorithm so you could be sure which index, or are okay with there being multiple "correct" answers.
What is the difference between these two:
string[,] array1;
and
string[][] array2;
Could someone please explain me about these two in terms of applications and functionality, memory management etc... how do you called them, which one is better to use? how to initialize them?
array1 is called a reference to a multidimensional array; array2 is a reference to a jagged array.
The first one is designed to store rectangular data which is not sparse and the number of elements in the dimensions are almost the same. You can initialize it like:
// Two-dimensional array.
int[,] array1= new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
In the latter case which is also called array of array the elements can be of different dimensions and sizes. Some times it is memory optimized to store sparse 2d data in the RAM. You can initialize it like:
int[][] array2= new int[][]
{
new int[] { 1, 3, 5, 7, 9 },
new int[] { 0, 2, 4, 6 },
new int[] { 11, 22 }
};
Absolutely the usage is depends on you requirements and purposes. You can review these 1, 2.
I'm building an interactive map using Mapbox and would like to draw a polygon over a specific area like is shown here. For this I need to dynamically fill a 3D array with the X,Y and Z coordinates from a database. The array structure I want to achieve is:
[
[
[
[xCoordinate1, yCoordinate1, zCoordinate1],
[xCoordinate2, yCoordinate2, zCoordinate2],
[xCoordinate3, yCoordinate3, zCoordinate3]
]
]
]
I have been trying to accomplish this with C#. In my application I initialized a 3D list, like so:
List<List<List<List<double>>>> coordinates = new List<List<List<List<double>>>>();
Next I iterated over the coordinates that are coming from the database so they would be added to the array:
foreach (var coordinate in Coordinates) {
coordinates.Add({ coordinate.X, coordinate.Y, coordinate.Z })
}
However this doesn't add the values at the disired position and throws an IndexOutOfBounds exception. I have also tried to initialize the array, like so:
double[, , ,] coordinates = {
{
{
{ coordinate.X, coordinate.Y, coordinate.Z },
{ coordinate.X, coordinate.Y, coordinate.Z },
{ coordinate.X, coordinate.Y, coordinate.Z }
}
}
};
With this approach i was also unable to format my array the way it should be formatted. Can someone show me how to work with a complex 3D array so that it gets the structure I'm looking for?
To sum up:
int[,,,] array3D = new int[,,,] {
{
{
{ 1, 2, 3 },
{ 4, 5, 6 }
//How can I add more here dynamically?
}
}
};
array3D[0, 0, 0, 3] = { 7, 8, 8 }; //This doesn't do the trick :(
You cannot change the size of a multidimensional array, but that is ok because your JSON really represents an array of arrays of sorts.
Start with the (expandable) list of coordinates
var coords = new List<double[]>
{
new double[] { 1,2,3 },
new double[] { 4,5,6 },
};
// later
coords.Add(new double[] { 7, 8, 9 });
Then convert to the JSON structure for export. You showed an array of array of array of coordinates (array).
var json = new double[][][][] {
new double[][][] {
coords.ToArray()
}
};
This is how you recover the coordinates
foreach (var item in json[0][0])
{
Debug.WriteLine($"Point=({item[0]}, {item[1]}, {item[2]})");
}
In the output window, you see
// Point=(1, 2, 3)
// Point=(4, 5, 6)
// Point=(7, 8, 9)
If I understand correctly, you can get away with just 2D list, where the first list contains sets of coordinates (i.e. (x,y,z)) and the second list simply contains a bunch of first lists, like so:
List<List<double>> coords = new List<List<double>>();
coords.Add(new List<double> { 24, 54, 46 });
coords.Add(new List<double> { 32, 45, 48 });
Console.WriteLine(coords[1][1]);
//Outputs 45.
//Note: xCoord = 24, yCoord = 54, zCoord = 46 in the first list entry
You can make it a separate method or an extension method where the coordinates are passed in as an arguments. It's also possible to loop through the lists to get particular x,y or z coordinate (if you need to search through them in your code).
I'm new at C# and I want to create a multidimensional array like this:
(source: parks.ca.gov)
But in 8x8x4 cells.
I want to store maze cells.
{
{1,1,1,0}, {1,0,0,0}, {1,1,1,1}, {1,0,0,0}, {1,1,0,1}, {1,1,0,1}, {0,1,0,0}, {1,0,0,1},
...
{0,1,1,0}, {1,0,1,0}, {0,0,1,1}, {1,0,1,0}, {1,0,0,1}, {0,1,0,1}, {1,1,1,0}, {1,1,0,1},
}
int[,,] table = new int[8,8,4]; // is this right?
table[0,0] = {0, 0, 1, 1}; // I want to fill it this way.
I'm aware it does not explicitly answer the question, but in my opinion you're shooting yourself in the foot by working with 3D arrays. C# is an OO language, so it really helps if you think OO.
Instead of working with a multidimensional array representing cells for you 3d Maze (if it is really a 3d maze you want), why not create a List of classes named Cell, each one containing their position and other stuff you need, like :
public class Cell
{
public Cell (int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public bool IsExplored { get; set; }
}
Then you can have a simple List<Cell> that you can iterate over.
You can also remove the x,y,z and create a Position class.
For walls, you can create an Enum and use bitwise operations, or store a list of Enum. Since you're a beginner, I'd suggest you the list of enums. You would have to add this Enum in the code, and this property to the Cell class :
public Enum WallPosition
{
Top,
Left,
Bottom,
Right
}
public List<WallPosition> walls { get; set;} //This goes into the Cell class
That way, every operation will be much much easier to do. For example, if you need to explore every cell at the column #3, you can do
foreach (Cell cell in yourCellList.Where(c => c.Y == 3))
{
cell.IsExplored = true;
}
Need to render every explored cell differently?
foreach (Cell cell in yourCellList.Where(c => c.IsExplored) { //Do stuff }
And so on.
No need for complicated for loops with your 3 dimensions, and a simple foreach is in my opinion far more readable than a
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
for (int k = 0; k < 4; k++)
every time you need to access your table.
The only ugly part would be to fill you list (By creating new Cell instances), but it would still be far more readable than a huge wall of { { { 0, 1, 0, 1 }, {1, 1, 1, 0} [...]
I'd also suggest that you read an introduction to OO principles.
With multidimensional arrays, you can either set them all at once (using basically the syntax you showed):
int[,,] table = {
{ { 1, 1, 1, 0 }, { 1, 0, 0, 0 } },
{ { 0, 1, 1, 0 }, { 1, 0, 1, 0 } }
};
or you can set the items one by one:
int[,,] table = new int[8,8,4];
table[0,0,0] = 0;
there is nothing in between. The best you could do is to write an extension method that would work something like this:
table.Set(0, 0, new int[] { 0, 0, 1, 1 });
As an alternative, you could use 2D array of arrays:
int[,][] table = {
{ new[] { 1, 1, 1, 0 }, new[] { 1, 0, 0, 0 } },
{ new[] { 0, 1, 1, 0 }, new[] { 1, 0, 1, 0 } }
};
or you could use almost the syntax you proposed:
int[,][] table = new int[8,8][];
table[0,0] = new[] { 0, 0, 1, 1 };
A disadvantage of this approach is that it doesn't force the inner arrays to be all the same length.
As proposed in comments, another option would be use a custom type like Cell and have a 2D array of those. Doing that makes it clearer what the array actually means, table[0,0].Left is certainly more readable than table[0,0,1].
If the wall can be there or not, you shouldn't use int values 0 and 1, you should use bool values false and true. If you want to have more states, an enum might be appropriate.
Your structure contains a lot of duplication, since bottom of a cell is the same as top of the cell below it (unless you want to have one way walls). This means the structure can get into an inconsistent state, which is often hard to debug (“The wall isn't there? But I just looked and it is there.”).
One way to avoid that would be store walls instead of cells. Instead of 8×8 cells, you would have 8×9 horizontal walls and 9×8 vertical walls. You could then have methods that would abstract this away, so you could easily look up walls of a particular cell.
An array initializer for a 3D array would look like this:
int[,,] table = {
{ {1,1,1,0}, {1,0,0,0}, ... },
{ {0,1,1,0}, {1,0,1,0}, ... },
...
};
The first line is right. The second line won't work. The closest thing is to use a 2D array of arrays:
int[,][] table = new int[8,8][];
table[0,0] = new int[] {0, 0, 1, 1};
Like #tigrou and #Pierre-Luc Pineault suggested, it would be a lot cleaner to encapsulate each cell in an object instead of a plain array.
Consider storing the data in an external file and reading it in instead of hardcoding the 256 numbers.
I know that they are used to store data, but I have a difficult time understanding exactly how to use them in a program.
In addition, I found this site with a tetris clone tutorial (the actual tutorial is missing). It uses arrays, but I can't really make sense of how it works.
Here's an example of the code -
public int[, ,] TShape = new int[4, 4, 2]
{
{{1, 0}, {0, 1}, {1, 1}, {2, 1}},
{{1, 0}, {0, 1}, {1, 1}, {1, 2}},
{{0, 0}, {1, 0}, {2, 0}, {1, 1}},
{{0, 0}, {0, 1}, {1, 1}, {0, 2}}};
Could it be that I'm looking too hard into this, or perhaps there's something I'm not grasping about it?
It would be clearer if formatted this way:
public int[, ,] TShape = new int[4, 4, 2]
{
{ {1, 0}, // <- this is int[2]
{0, 1},
{1, 1},
{2, 1} }, // <- the last four lines are an int[4,2]
{ {1, 0},
{0, 1},
{1, 1},
{1, 2} }, // <- another int[4,2]
{ {0, 0},
{1, 0},
{2, 0},
{1, 1} }, // <- third int[4,2]
{ {0, 0},
{0, 1},
{1, 1},
{0, 2} } // <- fourth and last int[4,2]
}; // <- The whole thing is int[4, 4, 2]
"Well I've been having a hard time
understanding how to use arrays. I
know they are used for storing data,
but I have yet to find any resource
that gives a clearer explanation than
that."
I'll try to give you an analogy: array is to programming like a file cabinet is to an office. The only difference is that a file cabinet is restricted to what it can hold: i.e. files... the only restriction for arrays is that it must hold items of the same type, but the actual type of the item can be nearly anything. Arrays can not only hold data, but objects, other arrays, other containers, etc.
So what can you do with an array in programming? Well a LOT of stuff! Let's look at several examples:
Financial: an array can hold the stock prices for today.
Gaming: an array can hold the 3D models that are used on a level.
Military: an array can hold all of the targets identified by a targeting system.
etc...
The main purpose of arrays is to contain various things and allow us to iterate over them. For example:
// Financial
int[] stockPrices = new int[4]{ 15, 14, 18, 16 }; // contains four prices
foreach( int price in stockPrices )
{
MakeTransaction(price);// calls a function that makes a transaction at the price: e.g. buy/sell
}
// Gaming
3DModel[] gameModels = new 3DModel[4]{ new Tank(), new Truck(), new Soldier(), new Building()}; // contains 3D models
foreach( 3DModel model in gameModels )
{
model.Draw();// calls a function of each 3DModel that draws the model on the screen
}
// Military
Target[] targets = new Target[4]{ new Tank(), new Helicopter(), new APC(), new Truck()}; // contains targets
foreach( Target target in targets )
{
Attack(target);// calls an attack function which initiates an attack on each target
}
The possibilities are endless! Arrays are a subset of containers and containers are an integral part of programming. Does that help?
Straight from the horse's mouth: http://msdn.microsoft.com/en-us/library/system.array.aspx
Those details will come in handy after you have gone through online tutorials such as this http://www.functionx.com/csharp/Lesson21.htm
Imagine you have 10 boxes. Now you want to clearly tell someone which box you are talking about. So you assign numbers to them, from 0 to 9. What you have now is an array of boxes, defined as:
box[ 10 ]
The number in the brackets tells you, how many of them are there. By default they are numbered from 0 to 9 (some languages allow to change this, but lets skip that for now). So if you are talking about the fifth box, its box[ 4 ] (since we index from 0!). Now imagine you open the box and see that there are five balls in it. This defines an array:
box[ 10 ][ 5 ]
A two dimensional array. How do you tell your friend which ball do you want to talk about? Again, you number them, this time from 0 to 4. How do you specify say the third ball in the seventh box? Simple: box[ 6 ][ 2 ]. And so on. Hope that helps.
In your question, you're stating the Tetris game which uses an array. That is a good use of arrays in whatever language you're using.
You have to see the Tetris play yard as the array. Let's say this play yard is a 20 spaces on the X axis, and 100 spaces on the Y axis. What tells you whether you have a piece on a space, is when you have the integer value 1, and you get an integer value of 0 for empty spaces. We then get:
var tetrisPlayYard = new int[20][100];
You now have to initialize each positions of the board to 0 in order to mark them as empty spaces, so no pieces have ever been placed already.
for(int xAxisIndex = 0; xAxisIndex < tetrisPlayYard.GetLength(0); ++xAxisIndex )
for (int yAxisIndex = 0; yAxisIndex < tetrisPlayYard.GetLength(1); ++ yAxisIndex)
tetrisPlayYard[xAxisIndex][yAxisIndex] = 0;
We now know that no pieces is on board as each array's positions are set to 0.
Then, when we place, let's say a four spaces straight line horizontally at the bottom-right of the board, we would then have to address 4 spaces, and set their values to 1 to indicate there is a piece on these spaces.
tetrisPlayYard[19][99] = 1;
tetrisPlayYard[18][99] = 1;
tetrisPlayYard[17][99] = 1;
tetrisPlayYard[16][99] = 1;
This tells that you have a four spaces straight line. Your algorithm should work around this logic to display the bars, the cubes, etc. while playing the game.
In conclusion, use arrays whenever a finite space is known, and that you know that it won't be required to resize it dynamically. Otherwise, a Collection should be used.