public override string ToString() {
string matrixView = "";
for (int r=0; r<=this.rows; r++) {
for (int c=0; c<=this.columns; c++) {
}
}
return matrixView;
}
Note:
##################################
this.rows = row number
this.columns = column number
this.matrix= 2-dimensional array used as data store
##################################
In this code, I aim to make seem for example 4x4 matrix like:
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
[0 0 0 0]
Each newline must be started with "[". Values(this.columns times) and spaces(this.columns-1 times) must be printed. Finally, the line must be ended with "]\n"
And these operations above must be done this.rowstimes.
I think in this way. But nested loops always make me confuse. So, I tried several times but I couldn't be successful at it. And String.Concat threw NullReferenceExceptionwhen I tried to concaten matrixView with "[", "]\n" and this.matrix[r, c].ToString().
I think you are looking for something like this:
public override string ToString() {
// When building string, better use StringBuilder instead of String
StringBuilder matrixView = new StringBuilder();
// Note r < matrix.GetLength(0), matrix is zero based [0..this.rows - 1]
// When printing array, let's query this array - GetLength(0)
for (int r = 0; r < matrix.GetLength(0); r++) {
// Starting new row we should add row delimiter
if (r > 0)
matrixView.AppendLine();
// New line starts from [
matrixView.Append("[");
// Note r < matrix.GetLength(1), matrix is zero based [0..this.rows - 1]
for (int c = 0; c < matrix.GetLength(1); c++) {
// Starting new column we should add column delimiter
if (c > 0)
matrixView.Append(' ');
matrixView.Append(matrix[r, c]);
}
// New line ends with [
matrixView.Append("]");
}
return matrixView.ToString();
}
You could for example do something like:
for (int r=0; r<=this.rows; r++) {
var s = "[";
for (int c=0; c<=this.columns; c++) {
s += myValue.ToString() + " ";
}
s += "]";
Console.WriteLine(s);
}
But if you numbers are larger than 9 you might want to pad the numbers with spaces. It is not very efficient to do many small concatenations like this. But unless you do this very frequently it will not matter.
How can I print the following pattern with the for statement?
AAAA
AAAB
AABB
ABBB
BBBB
What I tried to do:
Code:
int stars = 4;
for (int row = stars; row >= 1; row--)
{
for (int i = 0; i < row; i++)
{
Console.Write("A");
}
Console.WriteLine();
}
You where almost there.
I made a small change in the first for loop to add another row (>= 1 to >= 0). We need 5 rows for 4 stars, 6 rows for 5 stars, etc.
Compared the second for loop to stars as well because we want 4 values on each row (when stars is 4).
Added an if statement to check if we need to write an A or B based on the iteration number of both loops.
See code below:
int stars = 4;
for(int i = stars; i >= 0; i--) {
for(int j = 0; j < stars; j++) {
if(i > j) {
Console.Write('A');
}
else {
Console.Write('B');
}
}
Console.WriteLine();
}
I can't get this answer:
*****
****
***
**
*
Multidimensional arrays, nested (do..while, while, for)
char[,] stars = new char[5, 3];
for (int i = 0; i < 5; i++)
{
for(int x=0;x<3;x++)
{
stars[i,x]=char.Parse("*");
Console.Write(stars[i, x]);
I want to get 5 "*" stars then 4 in a new Line then 3 in a new Line then 1 in a new Line
Here you need to understand pattern behind *.
star pattern in your program is,
0st Line : 5 starts //Considering starting index is 0
1st Line : 4 starts // starts = n starts - Line no. where n = 5
2nd Line : 3 starts
3rd Line : 2 starts
4th Line : 1 starts
i.e.
Number of stars in single line = n starts - Line number //
where n = 5
So your code will look like,
int n = 5;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - i; j++)
{ //^^^^^ n - i is key behind this * pattern
Console.Write("*");
}
Console.WriteLine();
}
As this is not about array indexing or address calculation but actual countable objects (stars), I feel that 1-based indexes make more sense here.
Also, the number of stars should be decreasing, so counting backwards makes more sense as well:
for (int numStars = 5; numStars >= 1; --numStars)
{
for (int star = 1; star <= numStars; ++star)
Console.Write("*");
Console.WriteLine();
}
I'm trying to get the maximum Submatrix Sum from given nxn matrices. From what I read around the algorithm have a complexity of n^3 (kadane). I tried to implement it in java using a code I found here on stackoverflow (written by Anders Gustafsson in C# in these post) but it seems to not always work.
my code is this:
public static void maxSubMatrix(int matrix[][]) {
// O(n^3) Max Sum Submatrix
int row = matrix.length;
int col = matrix[0].length; // Get the col-length by taking the length of
// row 0 (in programm the matrices will be n x n)
// Initialise maxSum
int maxSum = 0;
// Set left column
for (int left=0; left<col; left++) {
// Initialise array
int tempArray[] = new int[row];
// Set right column by left column (outer loop)
for (int right=left; right<col; right++){
// Calculate sum between current left-right for every row 'i'
for (int i=0; i<row; i++)
tempArray[i] = matrix[i][right];
// ----
// Find maximum sum in tempArray[]
int sum = maxSubArray(tempArray);
// Compare sum with maxSum so far, and update it if necessary
if (sum > maxSum) maxSum = sum;
}
}
System.out.println(maxSum);
}
// ==========================
public static int maxSubArray(int array[]){
// Kadane O(n) Max Sum Subarray
int maxSum = 0;
int tempSum = 0;
for (int i=0; i<array.length; i++){
int b = array[i];
if (tempSum + b > 0) tempSum += b;
else tempSum = 0;
maxSum = Math.max(maxSum, tempSum);
}
return maxSum;
}
I have three examples:
Matrix 1
-2 -3
-1 -4
Output is 0 (Also the empty 0x0 Matrix is a solution)
Matrix 2
2 -1
-2 -1
Output is 2
Matrix 3
-1 3
3 -1
Output is 3, but should be 4
Maybe someone can see the error. I'm also open to completely new idea to implement it.
You have just forgotten to add the next rigth element to the temp-array:
(int i=0; i<row; i++)
tempArray[i] += matrix[i][right];
Now everything's fine! ;)
Greetz
I have a 2-dimensional array with user-entered values. I need to find sum of the even elements in the diagonal of the array.
I know how to declare the array and get it filled by the user, but I'm not sure what even elements in the main diagonal really means.
I know I can find out if a number is even by saying:
if n / 2 == 0
Once I've reported the sum of the even elements in the diagonal, I would like to replace all 0 values in the array with ones.
Diagonal means all places where x and y cordinates are the same
Do if your array contains:
1 3 8 5
3 3 9 7
4 4 5 7
5 1 7 4
Then the diagonal are in bold.
Assuming the array is a square:
int sum = 0;
for(int i = 0; i < numOfArrayRows; i++)
{
//Use the mod operator to find if the value is even.
if(array[i][i] % 2 == 0)
sum += array[i][i];
//Change 0's to ones
for(int j = 0; j < numOfArrayCols; j++)
if(array[i][j] == 0)
array[i][j] = 1;
}
Also, next time add the "Homework" tag if you have a homework question :P
With a two-dimensional array it's really easy, since you don't need any index magic:
int a[N][N] = ...;
int sum = 0;
for(int i=0; i<N; ++i)
if(a[i][i] % 2 == 0) //or a[i] & 1, if you like, just check if it's dividable by 2
sum += a[i][i];
This C++ code shouldn't be that different in C or C#, but you should get the point. Likewise the second question would be as simple as:
int a[M][N] = ...;
for(i=0; i<M; ++i)
for(j=0; j<N; ++j)
if(a[i][j] == 0)
a[i][j] = 1;
And I suspec that the main diagonal is the one that begins with coordinates 0,0.
To replace 0 elements with 1 you would do something like:
if (array[i,j] == 0) array[i,j] == 1;
This sounds like homework - however I will help out :)
So if you have an 2D array, and in order to find the sum of the diagonal values, you will know that the indices of both of the values would match in order to provide you with each of the diagonal values.
To iterate through these you could use a simple loop that would sum up every diagonal value, as shown:
//Your Sum
int sum = 0;
//This will iterate and grab all of the diagonals
//You don't need to iterate through every element as you only need
//the diagonals.
for(int i = 0; i < sizeOfArray; i++)
{
//This will add the value of the first, second, ... diagonal value to your sum
sum += array[i,i];
}
To set each of the values that is 0 to 1, you could iterate through each element of the array and check if the value is 0, then set that value to 1, for example:
for(int i = 0; i < sizeOfArray; i++)
{
for(int j = 0; j < sizeOfArray; j++)
{
//Check if this value is 0;
//If it is 0, set it to 1, otherwise continue
}
}
int[,] array = new int[,] {{1,2,3},
{4,5,6},
{7,8,9}};
//Suppose you want to find 2,5,8
for(int row = 0; row < 3; row++)
{
for(int column = 0; column < 3; column++)
{
if((row == 0 && column == 1) || (row == 1 && column == 1) || (row == 2 && column == 1))
{
Console.WriteLine("Row: {0} Column: {1} Value: {2}",row + 1, column + 1, array[row, column]);
}
}
}
Here is the code you need, not much explain:
//Read the size of the array, you can get it from .Count() if you wish
int n = Convert.ToInt32(Console.ReadLine());
int[][] a = new int[n][];
//Reading all the values and preparing the array (a)
for (int a_i = 0; a_i < n; a_i++)
{
string[] a_temp = Console.ReadLine().Split(' ');
a[a_i] = Array.ConvertAll(a_temp, Int32.Parse);
}
//performing the operation (google what diagonal matrix means)
int PrimarySum = 0, SecondarySum = 0;
for (int i = 0; i < n; i++)
{
//The If condition is to skip the odd numbers
if (a[i][i] % 2 == 0) { PrimarySum += a[i][i]; }
//For the reverse order
int lastelement = a[i].Count() - 1 - i;
if (a[i][lastelement] % 2 == 0) { SecondarySum += a[i][lastelement]; }
}
//Get the absolute value
Console.WriteLine(Math.Abs(PrimarySum - SecondarySum).ToString());
Console.ReadKey();