C# .NET adding items dynamically to 2-D arrays? - c#

What is the most efficient to add items to a multi-dimensional array where you don't know the item count at the start?

You can use Array.GetLength method to get lenght of each dimension, then you can just populate your array using a simple for loop.
For example:
for(int x = 0; x < array.GetLength(0); x++)
{
for(int y = 0; y < array.GetLength(1); y++)
{
array[x,y] = "bla,bla...";
}
}

Related

Save the sum of each row of a matrix into an array

I have a matrix and I want to return an array containing as elements the sum of each row elements of the matrix.
int [] sum;
for (var i = 0; i < m; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Count; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
This is how I tried to do it but seems it is not working. Any ideas?
Use var m = a.GetLength(0); to get number of rows, and var n = a.GetLength(1); to get number of columns.
now that looks like a different story after you edit:
Actually the first problem would be a NullreferenceException because int[]sum is not initialized!
Anyway, so it seems that you have an array of arrays. In this case you would need the Length of the Pages array to save your results. The first loop iterates over it using i and will run until result.Pages.Length. For each i you have correctly implemented a second loop where you sum up the result.
int [] sum = new int[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}
If you collections are List's then you need to use Count instead of Length
The Linq solution would look like this:
int [] sum = result.Pages.Select(x=>x.Sum()).ToArray();
EDIT:
double? means that you have a nullable data type. This is different from the normal double. Furthermore the default value will be null That means that you need to initialize the value at position i in sum before you add up values, otherwise the result will be null.
double? [] sum = new double?[result.Pages.Length];
for (var i = 0; i < result.Pages.Length; i++)
{
sum[i] = 0;
for (var j = 0; j < result.Pages[i].Actual.Length; j++)
{
sum[i] += result.Pages[i].Actual[j];
}
}

C#:How can I compare between the sum of every row in 2D array?

I would like to know how can I check if the sum of every row in 2D array is equal to each other.
Edit: I tired the way Mike suggested but i still got the index out of range. What am I missing?
bool sumSame;
int sum3=0;
int sum4 = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
sum3 += arr[0, i];
}
for (int i = 0; i < arr.GetLength(0); i++)
{
sum4 = 0;
for (int j = 0; j < arr.GetLength(1); i++)
{
**sum4 += arr[i, j];**//The Error is Here
}
if (sum4 != sum3)
{
sumSame = false;
break;
}
}
sumSame = true
You would like to know if all rows in a 2D array have the same sum.
So, you need to write a function which computes the sum of a row.
Then your problem becomes one-dimensional: check whether a function invoked for every element of a one-dimensional array returns the same value for each element. (The fact that an element is in turn another array is irrelevant.)
If you do not want to (or do not know how to) write a function, then you can write the code which computes the sum of a row as a nested loop, (as you already tried to do,) but still, it helps if you conceptually treat these two tasks as completely different from each other, meaning that they should not mix their variables, and the outer loop should only use the result of the calculation of the inner loop.
Generally, the way we make sure that all elements of an array are equal to a certain value is that we compute the value of the first element, (at index 0,) and then we loop for each subsequent element (for( int i = 1; ...) and check whether the value computed for this element is equal to the value that we got for the first element.
You can add the sum of each array to the List<int> and check the number of distinct results with Distinct().Count(), if it's 1 the results are the same for all 2D array.
int[,] arr = new int[,]
{
{1,2,3 },
{3,2,1 },
{2,3,1 }
};
List<int> sums = new List<int>();
for (int i = 0; i < arr.GetLength(0); i++)
{
int sum = 0;
for (int j = 0; j < arr.GetLength(1); j++)
{
sum += arr[i, j];
}
sums.Add(sum);
}
bool sameResults = sums.Distinct().Count() == 1;

How to assign value in two dimensional array

How to assign value in two dimensional array in c#
My Code is
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 5; y++)
{
matarix[x, y] = x+"-"+y;
}
}
i tried above code but its showing error "can't implicitly convert string to int"
How to do it ? Thanks
You're on the right track. Just assign a value.
int[,] matarix = new int[4, 5];
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 5; y++) {
matarix[x, y] = VALUE_HERE;
}
}
One recommendation I would make, would be to use Array.GetLength instead of hard coding your for loops. Your code would become:
int[,] matarix = new int[4, 5];
for (int x = 0; x < matarix.GetLength(0); x++) {
for (int y = 0; y < matarix.GetLength(1); y++) {
matarix[x, y] = VALUE_HERE;
}
}
You pass in one of the array's dimensions, and it tells you how many indices exist for that dimension.
This is a template I usually use for filling up two dimensional arrays.
Its one line and easy to change.
int[,] Foo = new int[4,5];
for(int i=0;i < Foo.Length; i++, Foo[i % Foo.GetLength(0),i / Foo.GetLength(1)] = 0; // Or value to assign
Also please do note that your array is holding integers while you are giving it strings (the "" converts it to a string, while x - y keeps it integer)
Hope it helps

Get objects at index out of List<Object>

I'm trying to make a 2D RPG game, and would like to use a List< List< Object > > to make a grid in which I store world objects of different types. Only problem is, that I don't know how to get stuff out of this multidimensional List.
The code below creates a multidimensional List and fills it with 'Dirt' Objects (though objects[i] doesnt work, which is my problem).
public List<List<Object>> objects;
this.mapWidth = 36;
this.mapHeight = 21;
this.objects = new List<List<Object>>();
for (int y = 0; y < mapHeight; y++)
{
objects.Add(new List<Object>());
}
for (var i = 0; i < mapWidth; i++)
{
for (var j = 0; j < mapHeight; j++)
{
objects[i].Add(new Dirt());
}
}
The players has a position, e.g. 18,11, which is in the middle of this map/multidimensional List. I would like to check which 'tiles' are around him so I only have to update those things on the map. List[y][x] doesnt work.
I think your initial construction code is incorrect. Looks like you're building your grid to have mapHeight rows and mapheight columns. Rewrite the construction code to be this:
for (var y = 0; y < mapHeight; y++)
{
objects.Add(new List<Object>());
for (var x = 0; x < mapWidth; x++)
{
objects[y].Add(new Dirt());
}
}
EDIT: And I think this will produce a table where your lookup can be achieved by: Object gridEntry = objects[y][x];
EDITx2: If you like, you can rewrite the creation code to this:
for (var y = 0; y < mapHeight; y++)
{
List<Object> currentRow = new List<Object>();
objects.Add(currentRow);
for (var x = 0; x < mapWidth; x++)
{
currentRow.Add(new Dirt());
}
}

How can I start initialization of "List of list" with columns

I have a list of list and I want to add values column oriented. Like in the following code sample:
Data = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
Data[j][i] = (probabilityList[j]) * K); // It won't work
}
}
I know it won't work because Data's index does not exist at current situation, and I need to use add() method.
However, I need to add values to list starts with columns:
[1 , null] ----> [1, null]
[null, null] [2, null]
How can I add values to a list of list starts with columns?
You need to create actual lists that you place inside your outer list of lists:
for (int i = 0; i < rowCount; i++)
{
Data.Add(new List<double>());
}
Once you've created all of the inner lists you can go through them and add values to them:
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
Data[j].Add((probabilityList[j]) * K);
}
}
Since you know the number of columns and rows you need you might think about using arrays instead of lists. When an array is initialized all members of the array are initialized to their default values. This would make your code
double[,] Data = new double[columnCount,rowCount];
for (int i = 0; i < columnCount - 1; i++)
{
for (int j = 0; j < rowCount - 1; j++)
{
Data[j,i] = (probabilityList[j]) * K);
}
}
You'll need to new up each element of the List of Lists
Data = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
List<double> column = new List<double>();
for (int j = 0; j < rowCount; j++)
{
//not really sure if this is the correct code here
//that would depend on your logic
column.Add((probabilityList[j]) * K);
}
Data.Add(column);
}
A list is not an array. It does not have slots that you just put elements in, it's more like a chain.
So initially you have a List<List<double>> that is empty, it has no List<double> instances in it. You have to (explicitly) create and add those lists to the Data list.
Alternatively, if you do need row and columns with slots for elements, you could use a two-dimensional matrix, like this:
var matrixData = new double[rowCount, columnCount];
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
matrixData[j, i] = ((probabilityList[j]) * K);
}
}
A popular way to initialize a list of lists (List<List<T>>) with one line of code is to use LINQ as follows:
List<List<double>> Data = Enumerable.Range(0, columnCount).Select(i => new List<double>()).ToList();
This will produce a list of empty initialized lists of double type. From here every inner list can be accessed as Data[i] and elements can be added to it as Data[i].Add(double).
Here is a breakdown of what LINQ methods do to initialize a List<List<double> >
Enumerable.Range(0, columnCount)
Returns IEnumerable collection of Int with the columnCount number of members.
.Select(i => new List<double>())
For each of the element of the collection returned by the previous step runs a function "new List()" and stores output (initialized empty List of double) in IEnumerable collection (so we get IEnumerable<List<double>> with columnCount number of members).
.ToList();
Converts the collection in the step above IEnumerable<List<double>> to List<List<double> - the desired output.
In short: You have to initialize each collection of List<T> inside of your parent List<T> collection.
As you may know, initialization of collections is done throw keyword new in .NET Framework. Otherwise, all inner Lists will be Null and you would not be able to access them.
I have applied this concept to your code.
var mainData = new List<List<double>>();
for (int i = 0; i < columnCount; i++)
{
var innerList = new List<double>();
for (int j = 0; j < rowCount; j++)
{
innerList.Add((probabilityList[j]) * K);
}
mainData.Add(innerList);
}

Categories

Resources