Create a empty array of points - c#

I'm trying to create a empty array of points, for this i'm using the following
Point[] listapontos = new[]; //should create a empty point array for later use but doesn't.
Point ponto = new Point(); //a no coordinates point for later use
for (int i = 1; i <= 100; i++) //cycle that would create 100 points, with X and Y coordinates
{
ponto.X = i * 2 + 20;
ponto.Y = 20;
listapontos[i] = ponto;
}
I'm having some trouble, because I can't create a empty array of points. I could create a empty array of strings using a list, but since i will need two elements, a list isn't useful here.
Any hints? (hints for the problem are also welcome)

// should create a empty point array for later use but doesn't.
No, what you've specified just isn't valid syntax. If you want an empty array, you could use any of:
Point[] listapontos = new Point[0];
Point[] listapontos = new Point[] {};
Point[] listapontos = {};
However, then you've got an array with 0 elements, so this statement:
listapontos[i] = ponto;
... will then throw an exception. It sounds like you should either use a List<Point>, or create an array of size 101:
Point[] listapontos = new Point[101];
(Or create an array of size 100, and change the indexes you use - currently you're not assigning anything to index 0.)
It's important to understand that in .NET, an array object doesn't change its size after creation. That's why it's often convenient to use List<T> instead, which wraps an array, "resizing" (by creating a new array and copying values) when it needs to.

I could create a empty array of strings using a list, but since i will
need two elements, a list isn't useful here.
You can define a class like this:
public class Point
{
public double X {get;set;}
public double Y {get;set;}
}
Then you can use a List<Point>:
List<Point> points = new List<Point>();
points.Add(new Point(){X=10, Y=20});

The reason this doesn't work is 2-fold.
Firstly, when you say
Point[] listapontos = new[];
you are using invalid syntax. It should be more like
Point[] listapontos = new Point[100];
Now, secondly, when you are writing into the array, you are never creating a new point.
Point is a class, which means it is passed by reference. This means that whenever you are writing Ponto's address in, but not a new Ponto.
Instead what you should do is something more like
for(int i = 0; i < 100; i++)
{
listapontos[i] = new Point(i * 2 + 20, 20);
}
By using the new keyword, you are creating a new point in memory and storing that point's address in the array, instead of writing the address to the same point 100 times into the array.

Related

Copy paste values within two different 2D arrays

Say I have this 2D array set up that shows the rotation state of the current Tetris block. How would I go about pasting these values into another bigger 2D array at any specified position? In this case the piece array is four blocks wide and tall, with a map that's ten blocks wide and 20 blocks tall. The value 0 in the example below stands for empty space, and 1 stands for a block piece.
// Array of block
blockMap = new int[4,4]{
{ 0,1,0,0},
{ 0,1,0,0},
{ 0,1,0,0},
{ 0,1,0,0},
};
You would write a double loop, copying each value to the larger array, using an offset to position the values. I.e. something like
blockMap = new int[4,4]{
{ 0,1,0,0},
{ 0,1,0,0},
{ 0,1,0,0},
{ 0,1,0,0},
};
var myLargeArray = new int[64, 64];
var offsetx = 3;
var offsety = 4;
// Note: GetLength is slow, so store values before looping
var sizex = blockMap.GetLength(0);
var sizey = blockMap.GetLength(1);
for(var x = 0; x < sizex; x++){
for(var y = 0; y < sizey; y++){
// Note: you might want to check if the target indices are valid
myLargeArray[x + offsetx, y + offsety] = blockMap[x, y];
}
}
I usually recommend writing your own 2D-array class that uses a 1D-array as storage, rather than using the build in multidimensional array. The reasons being that it is often useful to have data in a 1D array when interacting with other systems, and that the multidimensional array stores values column-major, while row-major is more common, at least in image processing. But these points are more relevant when dealing with larger amounts of data.

Why can't I create a multidimensional array of arrays?

My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.
In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].
Declaring string[][,] compiles with no problem but I can't initialize the variable:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors
The following errors are generated for the second line:
CS1586 Array creation must have array size or array initializer
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.
string[][,] multiArrayOfArrays; //No problemo
Here you just declare variable of specific type.
multiArrayOfArrays = new string[][8,8]; //Generates errors
And here you actually create new object of specific type. It generates errors because this is invalid syntax for multidimentional array initialization.
You need to specify size for first dimension [] and then initialize each element of that array with string[,].
Think of it as array of arrays:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[5][,];//create 5 elements of string[,] array
for (int i = 0; i < multiArrayOfArrays.Length; ++i)
{
multiArrayOfArrays[i] = new string[8,8];//actually fill elements with string[8,8]
}
or
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][,]
{
new string[8,8],
new string[8,8],
new string[8,8],
};
Probably you want a string[,][] a.
string[,][] a = new string[3, 4][];
a[0, 0] = new string[10];
a[0, 1] = new string[4];
a[1, 0] = new string[6];
string s = a[0, 0][2];
You have a special case of a jagged array, where the first array is 2-dimensional. It contains one-dimensional arrays of different sizes as elements.
The ordering of the array brackets might seem wrong, as the element type is usually on the left side of the brackets; however, if you think about on how you want to access elements, then it makes sense. First, you want to specify the 2 coordinates of the 2-dimensional board, then the single index of the pieces collection.
According to Jagged Arrays (C# Programming Guide), int[][,] jaggedArray4 = new int[3][,] "... is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes."

Cannot modify the return value of 'expression' because it is not a variable in a list but an array works [duplicate]

When I use an array of structs (for example System.Drawing.Point), I can get item by index and change it.
For example (This code work fine):
Point[] points = new Point[] { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Length; i++)
{
points[i].X += 1;
}
but when i use List it's not work:
Cannot modify the return value of
'System.Collections.Generic.List.this[int]'
because it is not a variable
Example(This code didn't work fine):
List<Point> points = new List<Point> { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++)
{
points[i].X += 1;
}
I know that when I get list item by index I got copy of it and compiler hints that I did not commit an error, but why take the elements of the array index works differently?
This is because for the array points[i] shows where the object is located. In other words, basically points[i] for an array is a pointer in memory. You thus perform operations on-the-record in memory, not on some copy.
This is not the case for List<T>: it uses an array internally, but communicates through methods resulting in the fact that these methods will copy the values out of the internal array, and evidently modifying these copies does not make much sense: you immediately forget about them since you do not write the copy back to the internal array.
A way to solve this problem is, as the compiler suggests:
(3,11): error CS1612: Cannot modify a value type return value of `System.Collections.Generic.List<Point>.this[int]'. Consider storing the value in a temporary variable
So you could use the following "trick":
List<Point> points = new List<Point> { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++) {
Point p = points[i];
p.X += 1;
points[i] = p;
}
So you read the copy into a temporary variable, modify the copy, and write it back to the List<T>.
The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.
Other words, when using the List<T>, you're are creating copies.
MSDN
Error Message
Cannot modify the return value of 'expression' because it is not a
variable
An attempt was made to modify a value type that was the result of an
intermediate expression. Because the value is not persisted, the value
will be unchanged.
To resolve this error, store the result of the expression in an
intermediate value, or use a reference type for the intermediate
expression.
Solution:
List<Point> points = new List<Point> { new Point(0,0), new Point(1,1), new Point(2,2) };
for (int i = 0; i < points.Count; i++)
{
Point p = points[i];
p.X += 1;
//and don't forget update the old value, because we're using copy
points[i] = p;
}

how to inset a new array to my jagged array

hello i will much apreciate any help.
ok let's see, first i have declare a jagged array like this and the next code
int n=1, m=3,p=0;
int[][] jag_array =new[n];
now my jagged array will have 1 array inside, next y have to fill the array like this:
car=2;
do
{
jag_array[p]= new double[car];
for (int t = 0; t < carac; t++)
{
jag_array[p][t] = variableX;
}
p=p+1
}
while(p==0)
now my jagged array looks like this(also insert some data for this example):
jag_array[0][0]=4
jag_array[0][1]=2
now my question how can i insert a new array whit out losing my previos data if i declare
jag_array[p+1]= new double[car];
i will lose the data from the previos one, i will like to look something likes this:
jag_array[0][0]=4
jag_array[0][1]=2
jag_array[1][0]=5
jag_array[1][1]=6
the reason i did not declare from the begining 2 array is beacuse i dont know how many i am going to use it could be just 1 or 20 and every time i have to create a new array whit out losing the previous data that has been already fill, thaks all for the attention,
The size of an array, once created, is by definition invariable. If you need a variable number of elements, use a List<T> - in your case, probably a List<int[]>.
The only alternative solution would be to created a new array with the new size (and assign that to your jag_array variable) and copy all the previous elements from your old array into the new array. That is unnecessarily complicated code when you can just use List<T>, but if you cannot use List<T> for any reason, here is an example:
// increase the length of jag_array by one
var old_jag_array = jag_array; // store a reference to the smaller array
jag_array = new int[old_jag_array.Length + 1][]; // create the new, larger array
for (int i = 0; i < old_jag_array.Length; i++) {
jag_array[i] = old_jag_array[i]; // copy the existing elements into the new array
}
jag_array[jag_array.Length - 1] = ... // insert new value here

C# - can you name a matrix with the contents of a string

Basically I have x amount of matrices I need to establish of y by y size. I was hoping to name the matrices: matrixnumber1 matrixnumber2..matrixnumbern
I cannot use an array as its matrices I have to form.
Is it possible to use a string to name a string (or a matrix in this case)?
Thank you in advance for any help on this!
for (int i = 1; i <= numberofmatricesrequired; i++)
{
string number = Convert.ToString(i);
Matrix (matrixnumber+number) = new Matrix(matrixsize, matrixsize);
}
You can achieve a similar effect by creating an array of Matrices and storing each Matrix in there.
For example:
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < numberofmatricesrequired; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
This will store a bunch of uniques matrices in the array.
If you really want to you could create a Dictionary<String, Matrix> to hold the matrices you create. The string is the name - created however you like.
You can then retrieve the matrix by using dict["matrix1"] (or whatever you've called it).
However an array if you have a predetermined number would be far simpler and you can refer to which ever you want via it's index:
Matrix theOne = matrix[index];
If you have a variable number a List<Matrix> would be simpler and if you always added to the end you could still refer to individual ones by its index.
I'm curious why you cannot use an array or a List, as it seems like either of those are exactly what you need.
Matrix[] matrices = new Matrix[numberofmatricesrequired];
for (int i = 0; i < matrices.Length; i++)
{
matrices[i] = new Matrix(matrixsize, matrixsize);
}
If you really want to use a string, then you could use a Dictionary<string, Matrix>, but given your naming scheme it seems like an index-based mechanism (ie. array or List) is better suited. Nonetheless, in the spirit of being comprehensive...
Dictionary<string, Matrix> matrices = new Dictionary<string, Matrix>();
for (int i = 1; i <= numberofmatricesrequired; i++)
{
matrices.Add("Matrix" + i.ToString(), new Matrix(matrixsize, matrixsize));
}

Categories