Save the sum of each row of a matrix into an array - c#

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];
}
}

Related

How to iterate object in loop C#?

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

Show sublist value from index C#

My problem is I have M subproblem. Each subproblem include x (double array) and reduced cost which has different value for each iteration m. I want to show x which has the minimum reduced cost among all subproblems. here is my class:
public class Subproblem
{
public double[,] x { get; set; }
public double ReducedCost { get; set; }
}
So far, I already can get the minimum Reduced Cost and index of it. Now I want to show x value (double array) which on that index. I've code like this:
var sub = new List<Subproblem>();
for (int m = 0; m < M; ++m)
{
Subproblem s = new Subproblem();
s.x = new double[DC1, DC1];
s.ReducedCost = model.ObjVal;
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
s.x[i, j] = x[i, j].X;
}
}
sub.Add(s);
}
double minRC = sub.Min(a => a.ReducedCost);
int minRCIndex = sub.FindIndex((i) => i.ReducedCost == minRC);
Console.WriteLine(sub.x(minRCIndex));
the last line (Console.WriteLine(sub.x(minRCIndex));) still got red underline, I don't know how to write it
If you are only trying to get the minimum Reduced Costed subproblem you should be doing:
Subproblem minimumReducedCostedSubproblem = sub[minRCIndex];
And you can print the matrix down like this:
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.Write(minimumReducedCostedSubproblem.x[i, j] + "\t");
}
Console.Write("\n");
}
But you seem a little confused. You are pushing a Subproblem into your sub list with the same object for M times. Because model.ObjVal doesn't change along the first for loop. There is something wierd going on there too.
It should be
var objWithMinReduceCost = sub[minRCIndex];
//Now you have the object of Subproblem derived from your logic.
//You can access x property of it have further logic to process it.
for (int i = 0; i < DC1; ++i)
{
for (int j = 0; j < DC1; ++j)
{
Console.WriteLine(objWithMinReduceCost.x[i, j]);
}
}
If you are interested in obtaining the double array, you could just do this:
double[,] result = sub.First(i => i.ReducedCost == minRC).x;
Although as Tolga mentioned, all your elements will have the same ReducedCost with your current code.

What is the most efficient way to find the largest element in a matrix along with position? Also, the largest element in each column with position

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

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 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