I initialized an object:
object[,] A = new object[range.RowCount() + 1, range.ColumnCount() + 1];
After filling this I need to iterate all elements of object in loop.
How to iterate this in for loop?
I tried to do: for(var i = 0; i < A.Count(); i++){}
But there is not property Count() for object, also this is matrix.
For things like this you might want nested loops, like so:
for (int i = 0; i < A.GetLength(0); i++)
{
for (int j = 0; j < A.GetLength(1); j++)
{
//do your magic
}
}
Arrays have Length property:
for (var i = 0; i < A.Length; i++)
{
var b = A[i, 1];
}
Count() is a method of IEnumerable
Related
I'm getting the error that the index for my array is out of range.
I define a 3D array like this:
Button[, ,] posAr_ItemManager = new Button[maxRows, maxColumns, maxCategories];
Where maxRows, maxColumns and maxCategories are all constant integers.
I then want to loop through this whole array, i do it using nested loops as shown here:
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; i < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; i < posAr_ItemManager.GetLength(2); z++)
{
if (posAr_ItemManager[i,j,z] != null)
{
Button but = posAr_ItemManager[i, j, z];
but.Width = itemWidth;
but.Height = itemHeight;
but.SetValue(Canvas.LeftProperty, itemPanelX + (i + 1) * butSpacing + i * itemWidth);
but.SetValue(Canvas.TopProperty, itemPanelY + (i+1)*butSpacing + i* itemHeight);
}
}
}
}
When I run the program it gives the out of range error where I check if the item is not equal to null.
I have no idea why it does it as I thought my declaration of the 3D array is correct and the nested loop as well? thanks in advance!
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; j < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; z < posAr_ItemManager.GetLength(2); z++)
look very carefully at the middle tests. Also, consider hoisting the GetLength tests so you only do them once per dimension. Perhaps:
int rows = posAr_ItemManager.GetLength(0), columns = posAr_ItemManager.GetLength(1),
categories = posAr_ItemManager.GetLength(2);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
for (int cat = 0; cat < categories; cat++)
You're using "i" to check if the loop is over in each of the dimensions. Change it to corresponded i,j,z.
for (int i = 0; i < posAr_ItemManager.GetLength(0); i++)
{
for (int j = 0; **j** < posAr_ItemManager.GetLength(1); j++)
{
for (int z = 0; **z** < posAr_ItemManager.GetLength(2); z++)
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];
}
}
I've been trying to iterate through an entire 2D array and count the number of 0s. How can I do this?
I'm sure I have to use the following to make the program work:
Use an outer for loop to iterate through the rows of the array
Use an inner for loop to iterate through the columns of the array
if matrix[row,col] == 0, increment a variable
To get the number of rows of the 2D array, use the method matrix.GetLength(0), and to get the number of columns of the array, use the method matrix.GetLength(1)
Here's what I have attempted so far:
public int Test9(int[,] matrix)
{
int b = 0;
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); i++)
{
b = matrix[i, j];
}
}
This is how you can do it..
public int Test9(int[,] matrix)
{
int zeroCounter = 0;
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
{
if(matrix[i, j] == 0)
{
zeroCounter++;
}
}
}
I have written the following code but it looks to be far from efficient.
//Find largest in tempRankingData
int largestIntempRankingData = tempRankingData[0, 0];
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] > largestIntempRankingData)
{
largestIntempRankingData = tempRankingData[i, j];
}
}
}
//Find position of largest in tempRankingData
List<string> positionLargestIntempRankingData = new List<string>();
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] == largestIntempRankingData)
{
positionLargestIntempRankingData.Add(i + "," + j);
}
}
}
//Find largest in each column
int largestInColumn = 0;
List<string> positionOfLargestInColumn = new List<string>();
Dictionary<int, List<string>> position = new Dictionary<int, List<string>>();
for (int i = 0; i < count; i++)
{
largestInColumn = tempRankingData[0, i];
positionOfLargestInColumn = new List<string>();
for (int j = 0; j < count; j++)
{
if (tempRankingData[j, i] > largestInColumn)
{
largestInColumn = tempRankingData[j, i];
}
}
for (int j = 0; j < count; j++)
{
if (tempRankingData[j, i] == largestInColumn)
{
positionOfLargestInColumn.Add(j + "," + i);
}
}
position.Add(i, positionOfLargestInColumn);
}
So, I wanted to check about the most efficient way to do this.
Whilst you're finding the largest in each column, you could also be finding the largest overall. You can also capture the positions as you go:
//Find largest in each column
int largestInColumn = 0;
int largestOverall = int.MinValue;
List<string> positionOfLargestInColumn;
Dictionary<int, List<string>> position = new Dictionary<int, List<string>>();
List<string> positionLargestIntempRankingData = new List<string>();
for (int i = 0; i < count; i++)
{
largestInColumn = tempRankingData[0, i];
positionOfLargestInColumn = new List<string>();
positionOfLargestInColumn.Add("0," + i);
for (int j = 1; j < count; j++)
{
if (tempRankingData[j, i] > largestInColumn)
{
largestInColumn = tempRankingData[j, i];
positionOfLargestInColumn.Clear();
positionOfLargestInColumn.Add(j + "," + i);
}
else if(tempTankingData[j,i] == largestInColumn)
{
positionOfLargestInColumn.Add(j + "," + i);
}
}
position.Add(i, positionOfLargestInColumn);
if(largestInColumn > largestOverall)
{
positionLargestIntempRankingData.Clear();
positionLargestIntempRankingData.AddRange(positionOfLargestInColumn);
largestOverall = largestInColumn;
}
else if(largestInColumn == largestOverall)
{
positionLargestIntempRankingData.AddRange(positionOfLargestInColumn);
}
}
1). You can find largest element and its position in one method and retrieve.
Would be caller of your method concerned about position or actual value, is a matter of concrete case.
2) You can use `yield return' technique in your matrix search (for column based search), so do not compute all column's maximas and push them into the dictionary. Dictionaries are not that fast as arrays, if you can avoid use them, do that.
3) You can keep a matrix in single dimension, long array. Have [] access operator overload, to "emulate" matrix access. Why ? If finding maximum is something frequent you might need to do during program run, having one foreach loop is faster then having 2 nested once. In case of a big matrices, single array search can be easily parallelized among different cores.
If big matrices and/or frequent calls are not your concern, just simplify your code like in points (1), (2).
For your fist two itterations you could replace with this:
//Find largest in tempRankingData
int largestIntempRankingData = tempRankingData[0, 0];
List<KeyValuePair<double,string>> list = new List<KeyValuePair<double,string>>();
for (int i = 0; i < count; i++)
{
for (int j = 0; j < count; j++)
{
if (tempRankingData[i, j] > largestIntempRankingData)
{
largestIntempRankingData = tempRankingData[i, j];
list.Add(new KeyValuePair<double, string>(largestIntempRankingData, i + "," + j)); //Add the value and the position;
}
}
}
//This gives a list of strings in which hold the position of largestInItemRankingData example "3,3"
//Only positions where the key is equal to the largestIntempRankingData;
list.Where(w => w.Key == largestIntempRankingData).ToList().Select(s => s.Value).ToList();
You can get all these pieces of information in a single scan with a little fiddling around. Something like this (converting the rows and columns to a string is trivial and better done at the end anyway):
int? largestSoFar = null; // you could populate this with myMatrix[0,0]
// but it would fail if the matrix is empty
int largestCol = 0;
int largestRow = 0;
int?[] largestPerColumn = new int?[numOfCols]; // You could also populate this with
// the values from the first row but
// it would fail if there are no rows
int[] largestColumnRow = new int[numOfCols];
for (int i = 0; i < numOfRows; i++)
{
for (int j = 0; j < numOfCols; i++)
{
if (largestSoFar < myMatrix[i,j])
{
largestSoFar = myMatrix[i,j];
largestCol = j;
largestRow = i;
}
if (largestPerColumn[j] < myMatrix[i,j])
{
largestPerColumn[j] = myMatix[i,j];
largestColumnRow[j] = i;
}
}
}
// largestSoFar is the biggest value in the whole matrix
// largestCol and largestRow is the column and row of the largest value in the matrix
// largestPerColumn[j] is the largest value in the jth column
// largestColumnRow[j] is the row of the largest value of the jth column
If you do need to capture all the "maxima" (for want of a better word, because that's not really what you are doing) in a column, you could just change the above code to something like this:
int? largestSoFar = null; // you could populate this with myMatrix[0,0]
// but it would fail if the matrix is empty
int largestCol = 0;
int largestRow = 0;
int?[] largestPerColumn = new int?[numOfCols]; // You could also populate this with
// the values from the first row but
// it would fail if there are no rows
List<int>[] largestColumnRow = new List<int>[numOfCols];
for (int i = 0; i < numOfRows; i++)
{
for (int j = 0; j < numOfCols; i++)
{
if (largestSoFar < myMatrix[i,j])
{
largestSoFar = myMatrix[i,j];
largestCol = j;
largestRow = i;
}
if (largestPerColumn[j] < myMatrix[i,j])
{
largestPerColumn[j] = myMatix[i,j];
largestColumnRow[j].Add(i);
}
}
}
// Now largestColumnRow[j] gives you a list of all the places where you found a larger
// value for the jth column
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);
}