C# how to do arithmetic operations on a 2d Array matrix - c#

I've been toying with this code which prints a small matrix with negative and positive numbers,
I would like an efficient way to add together only the positive elements on the matrix and get the product of such elements also do the same but after a specific number, such as the highest on the matrix
static void Main(string[] args)
{
int row = 5;
int column = 5;
int[,] array = new int[row, column];
Random rand = new Random();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
array[i, j] = rand.Next(-5, 10);
}
}
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(array[i, j].ToString() + " ");
}
Console.WriteLine(" ");
}
Console.ReadLine();
}

To filter and add positive matrix elements, you could do something like the following:
static void Main(string[] args)
{
const int rows = 5;
const int columns = 5;
var array = new int[rows, columns];
var rand = new Random();
int sum = 0;
bool numberSeen = false;
int numberToSee = 1;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
var cell = rand.Next(-5, 10);
if (!numberSeen && (cell == numberToSee))
{
numberSeen = true;
}
array[row, col] = cell;
if (numberSeen && (cell > 0))
{
sum += cell;
}
}
}
Console.WriteLine($"sum = {sum}");
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Console.Write(array[row, col].ToString() + " ");
}
Console.WriteLine(" ");
}
Console.ReadLine();
}

Related

How to give the reverse diagonal rows and columns color in a 2D array in c#?

for school i have made an 2D array. All numbers that are diagonal needs to be the color red, which works. Now i want to print all reverse diagonal columns and rows yellow. Here is some code: In the method DisplayMatrixWithCross it has to be made.
using System.Data.Common;
namespace assignment1
{
internal class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("invalid number of arguments!");
Console.WriteLine("usage: assignment[1-3] <nr of rows> <nr of columns>");
return;
}
int numberOfRows = int.Parse(args[0]);
int numberOfColumns = int.Parse(args[1]);
Program myProgram = new Program();
myProgram.Start(numberOfRows, numberOfColumns);
}
void Start(int numberOfRows, int numberOfColumns)
{
int[,] matrix = new int[numberOfRows, numberOfColumns];
InitMatrixLinear(matrix);
DisplayMatrix(matrix);
DisplayMatrixWithCross(matrix);
}
void InitMatrix2D(int[,] matrix)
{
int element = 1;
for (int r = 0; r < matrix.GetLength(0); r++)
{
for (int c = 0; c < matrix.GetLength(1); c++)
{
matrix[r, c] = element++;
}
}
}
void DisplayMatrix(int[,] matrix)
{
for (int r = 0; r < matrix.GetLength(0); r++)
{
for (int c = 0; c < matrix.GetLength(1); c++)
{
Console.Write($"{matrix[r, c]:00} ");
}
Console.WriteLine();
}
}
void InitMatrixLinear(int[,] matrix)
{
int element = 1;
for (int i = 0; i < matrix.Length; i++)
{
int r = (element - 1) / matrix.GetLength(0);
int c = (element - 1) % matrix.GetLength(1);
matrix[r, c] = element;
element++;
}
}
void DisplayMatrixWithCross(int[,] matrix)
{
Console.WriteLine();
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
if (rows == columns)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"{matrix[rows, columns]:00} ");
}
/* else if ()
{
Console.BackgroundColor = ConsoleColor.Yellow;
}*/
else
{
Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{matrix[rows, columns]:00} ");
}
}
Console.WriteLine();
}
}
}
}
Cant get it to work sadly, can anyone help
You can calculate the value that goes in each spot, no need to keep a separate counter variable:
void InitMatrix2D(int[,] matrix)
{
for (int r = 0; r < matrix.GetLength(0); r++)
{
for (int c = 0; c < matrix.GetLength(1); c++)
{
matrix[r, c] = (r * matrix.GetLength(1)) + (c + 1);
}
}
}
void InitMatrixLinear(int[,] matrix)
{
for (int i=0; i<matrix.Length; i++)
{
int r = i / matrix.GetLength(1);
int c = i % matrix.GetLength(1);
matrix[r, c] = (i+1);
}
}
Next, you can use matrix.Length to determine the correct amount of zeroes to pad your numbers with:
void DisplayMatrix(int[,] matrix)
{
int maxLength = matrix.Length.ToString().Length;
String numFormat = new string('0', maxLength);
for (int r = 0; r < matrix.GetLength(0); r++)
{
for (int c = 0; c < matrix.GetLength(1); c++)
{
Console.Write(matrix[r, c].ToString(numFormat) + " ");
}
Console.WriteLine();
}
}
Lastly, for the reverse diagonal, if the one-based row number plus the zero-based column number equals the number of columns, then you can change the background to yellow:
void DisplayMatrixWithCross(int[,] matrix)
{
int maxLength = matrix.Length.ToString().Length;
String numFormat = new string('0', maxLength);
Console.WriteLine();
for (int rows = 0; rows < matrix.GetLength(0); rows++)
{
for (int columns = 0; columns < matrix.GetLength(1); columns++)
{
Console.ResetColor();
if (rows == columns)
{
Console.ForegroundColor = ConsoleColor.Red;
}
if ((rows+1)+columns == matrix.GetLength(1))
{
Console.BackgroundColor = ConsoleColor.Yellow;
}
Console.Write(" " + matrix[rows, columns].ToString(numFormat));
}
Console.WriteLine();
}
}
My output:

Stop iteration in a 2d matrix with break

I was wondering how can I stop the iteration through the rows and columns of a 2d matrix if a value is found.
int[,] matrix = new int[8, 10];
Random rnd = new Random();
bool value = false;
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
int number = rnd.Next(1, matrix.Length + 1);
matrix[row, col] = number;
Console.Write("{0,3}", number);
if (number == 8)
{
value = true;
break;
}
}
}

How to get all possible 2x2 sub matrices in a 3x3 matrix in C#?

If matrix A of size (3x3), then should i use the method of finding determinants, like grabbing the rows and column of first element and removing it from the array 2D array to get the remaining elements and then moving to the next element and repeating the same steps ?
[{1,2,3},
{4,5,6},
{7,8,9}]
I finally was able to do it, here's what I did :
enter image description here
class program
{
public static void Main()
{
int[,] arr = new int[3, 3];
Console.WriteLine("Enter elements of " + (arr.GetUpperBound(0) + 1) + "x" + (arr.GetUpperBound(1) + 1) + " matrix:");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
arr[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine("Matrix entered: ");
for (int i = 0; i < (arr.GetUpperBound(0) + 1); i++)
{
for (int j = 0; j < (arr.GetUpperBound(1) + 1); j++)
{
Console.Write("\t" + arr[i, j]);
}
Console.WriteLine();
}
Console.WriteLine("Possible sub-matrices: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j< 3; j++)
{
TrimArray(i,j,arr);
}
}
}
public static int[,] TrimArray(int row, int column, int[,] original)
{
int[,] resultant = new int[original.GetLength(0) - 1, original.GetLength(1) - 1];
for (int i = 0, j = 0; i < original.GetLength(0); i++)
{
if (i == row)
continue;
for (int k = 0, u = 0; k < original.GetLength(1); k++)
{
if (k == column)
continue;
resultant[j, u] = original[i, k];
u++;
}
j++;
}
Console.WriteLine();
for (int i = 0; i < 2; i++)
{
for (int j = 0; j< 2; j++)
{
Console.Write("\t"+resultant[i,j]);
}
Console.WriteLine();
}
return resultant;
}
}
I did this for you yesterday, I created a method that will return a square matrix, given a parent matrix and the length.
static void Main(string[] args)
{
int[][] parentMatrix = new int[][]
{
new int [] { 1, 2, 3 },
new int [] { 4, 5, 6 },
new int [] { 7, 8, 9 }
};
var chunks = GetSubMatrices(parentMatrix, 2);
Console.WriteLine(chunks);
}
static List<int[][]> GetSubMatrices(int[][] parentMatrix, int m)
{
int n = parentMatrix.Length > m ? parentMatrix.Length : throw new InvalidOperationException("You can't use a matrix smaller than the chunk size");
var chunks = new List<int[][]>();
int movLimit = n - m + 1;
var allCount = Math.Pow(movLimit, 2);
for (int selRow = 0; selRow < movLimit; selRow ++)
{
for (int selCol = 0; selCol < movLimit; selCol ++)
{
// this is start position of the chunk
var chunk = new int[m][];
for (int row = 0; row < m; row++)
{
chunk[row] = new int[m];
for (int col = 0; col < m; col++)
{
chunk[row][col] = parentMatrix[selRow + row][selCol + col];
}
}
chunks.Add(chunk);
}
}
return chunks;
}
If you have any problems using it, you can simply comment below.
I needed to solve a problem like and came up with this answer. Hope it adds to your library of answers. If the submatrix specified is not greater than 1, do nothing.
public static void GetSubMatrixes(int[,] arr, int size)
{
int parentMatrixRowLength = arr.GetLength(0);
int parentMatrixColLength = arr.GetLength(1);
var overall = new List<object>();
if(size > 1)
{
for (int i = 0; i < parentMatrixRowLength; i++)
{
//get the columns
for (int j = 0; j < parentMatrixColLength; j++)
{
var subMatrix = new int[size, size];
/*if the new matrix starts from second to the last value in either the row(horizontal or column)
* do not proceed, go to the row or column in the parent matrix
* */
if (j < parentMatrixColLength - (size - 1) && i < parentMatrixRowLength - (size - 1))
{
//add
for (int m = 0; m < subMatrix.GetLength(0); m++)
{
for (int n = 0; n < subMatrix.GetLength(1); n++)
{
/*check the sum of current column value and the sum of the current row value
* of the parent column length and row length if it goes out of bounds
*/
var row = i + m; var col = j + n;
//actual check here
if (row < parentMatrixRowLength && col < parentMatrixColLength)
{
subMatrix[m, n] = arr[i + m, j + n];
}
}
}
overall.Add(subMatrix);
}
}
}
//display the sub matrixes here
for (int i = 0; i < overall.Count; i++)
{
var matrix = overall[i] as int[,];
for (int y = 0; y < matrix.GetLength(0); y++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
Console.Write(string.Format("{0} ", matrix[y, x]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.WriteLine();
}
}
}

matrix, sub matrix with greatest sum

The task:
1. Make a matrix n by m and fill it with data from console.
2. Find the 3*3 sub matrix with the greatest sum.
{
static int[,] ArrayReadConsole()
{
Console.WriteLine("please enter n:");
int n;
n = Int32.Parse(Console.ReadLine());
Console.WriteLine("please enter m:");
int m;
m = Int32.Parse(Console.ReadLine());
int[,] data = new int[n, m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
Console.WriteLine("please enter a new value");
int number;
number = Int32.Parse(Console.ReadLine());
data[i, j] = number;
}
}
return data;
}
static void SumOfPlatform(int[,] data)
{
int sum =0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum =+ data[i + k, j + l];
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum =0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}",maxSum,x,y );
}
static void Main()
{
int[,] data = ArrayReadConsole();
SumOfPlatform(data);
}
}
}
I wrote that code but something went wrong... It doesn't find position or sum of the matrix I enter. I know that 4x for loop is a bad idea just I didn't want to make another method just for that. Any idea why it doesn't work?
Your Code for SumOfPlatform is working with only change from =+ to +=
static void SumOfPlatform(int[,] data)
{
int sum = 0;
int x = 0;
int y = 0;
int maxSum = 0;
for (int i = 0; i < data.GetLength(0) - 2; i++)
{
for (int j = 0; j < data.GetLength(1) - 2; j++)
{
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
sum += data[i + k, j + l]; //only Change
}
}
if (maxSum < sum)
{
maxSum = sum;
x = i;
y = j;
}
sum = 0;
}
}
Console.WriteLine("Sum: {0}\nPosition: {1} {2}", maxSum, x, y);
}
static void Main(string[] args)
{
// int[,] data = ArrayReadConsole();
int[,] data = new int[,]
{
{1,4,6,7,3,5,7,4 },
{1,4,5,3,3,5,4,4 },
{1,1,6,2,1,5,7,4 },
{1,3,6,3,3,5,2,4 },
{1,4,6,2,3,5,3,4 },
{1,4,2,2,3,5,3,4 },
{1,4,3,3,3,5,2,4 },
{1,4,4,3,3,5,2,4 }
};
SumOfPlatform(data);
}

filling matrix with user's input in C#

i wanna fill a matrix in C# with user's inputs,but i have trouble with it.when i enter rows and cols equal with each other,it work; but when i enter rows and cols different with each other the program stop . the code is
int row = 0;
int col = 0;
int[,] matrix1;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
matrix1=new int[row,col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine());// i have problem with this line,... plz show me the correct form
}
}
You allocate memory before you input array size.
Correct code:
int row = 0;
int col = 0;
int[ , ] matrix1;
row = Convert.ToInt16( Console.ReadLine( ) );
col = Convert.ToInt16( Console.ReadLine( ) );
matrix1 = new int[ row, col ];
Console.WriteLine( "enter the numbers" );
for ( int i = 0; i < col; i++ )
{
for ( int j = 0; j < row; j++ )
{
matrix1[ i, j ] = Convert.ToInt16( Console.ReadLine( ) );
}
}
You initialized your matrix as a 0x0 matrix. Which is an empty matrix so you can't add or read anything from it.
Try this
int row = 0;
int col = 0;
int[,] matrix1;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
matrix1=new int[row,col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine()); } }
int row;
int col;
row = Convert.ToInt16(Console.ReadLine());
col = Convert.ToInt16(Console.ReadLine());
int[,] matrix1 = new int[row, col];
Console.WriteLine("enter the numbers");
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
matrix1[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
int col = Convert.ToInt32(Console.ReadLine());
int row = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[row, col];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"enter row{i} and col{j} ");
matrix[i, j] = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine();
}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j]);
}
Console.WriteLine();
}

Categories