how do i display the table for a 2D array? - c#

I need to fill an array and display that array to the console (in table format).
Here is what I have so far:
static void Main()
{
//Declare variables, strings and constants.
const int ROWS = 10;
const int COLS = 5;
const int MIN = 1;
const int MAX = 100;
int total = 0;
int[,] numbers = new int[ROWS, COLS];
Random rand = new Random();
//Populate the array
for (int r = 0; r < ROWS; ++r)
{
for (int c = 0; c < COLS; ++c)
{
numbers[r, c] = rand.Next(MIN, MAX + 1);
}
}
//Display the array to console (table format)
for (int r = 0; r < numbers.GetLength(0); ++r)
{
for (int c = 0; c < numbers.GetLength(1); ++c)
{
Console.Write("{0,6} ", numbers[r, c]);
if (c % 5 == 0) Console.WriteLine();
}
}
When i do this, my display if off by 1 and doesn't align properly for a 10x5 table.

You could check if the column index plus one, c + 1, is equal to the given column count, COLS, then write a new line:
if (c + 1 == COLS) Console.WriteLine();
Another way is to print a new line after all columns are printed:
for (int r = 0; r < numbers.GetLength(0); ++r)
{
for (int c = 0; c < numbers.GetLength(1); ++c)
{
Console.Write("{0,6} ", numbers[r, c]);
}
Console.WriteLine();
}

This happens because of your next line:
if (c%5 == 0) Console.WriteLine();
Notice that the first output, r=0, c=0, so it prints a new line

Related

how can i sort a matrix's each row from smallest to largest and then find the matrix's peak value?

i need to write a program that takes 1 to 100 integers randomly, then i need to take this program's transpose, then I need to sort this matrix (each row in itself) from smallest to largest.
and finally, i need to find this matrix's peak value. here is what i have written for the program. for now, it creates a random matrix (20x5) and then it takes its transpose. can you help me with finding its peak value and then sort its each row?
PS.: using classes is mandatory!
using System;
namespace my_matrix;
class Program
{
public int[,] Create(int[,] myarray, int Row, int Clm)
{
Random value = new Random();
myarray = new int[Row, Clm];
int i = 0;
int j = 0;
while (i < Row)
{
while (j < Clm)
{
myarray[i, j] = value.Next(1, 100);
j++;
}
i++;
j = 0;
}
return myarray;
}
public int[,] Print(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====ARRAY=====");
for (int a = 0; a < Row; a++)
{
for (int b = 0; b < Clm; b++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
public int[,] Transpose(int[,] myarray, int Row, int Clm)
{
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return myarray;
}
public int[,] Print_Transpose(int[,] myarray, int Row, int Clm)
{
Console.WriteLine("=====TRANSPOSE=====");
for (int b = 0; b < Clm; b++)
{
for (int a = 0; a < Row; a++)
{
Console.Write(myarray[a, b] + " ");
}
Console.WriteLine();
}
return null;
}
static void Main(string[] args)
{
Program x = new Program();
int[,] myarray = new int[20, 5];
int[,] a = x.Create(myarray, 20, 5);
x.Print(a, 20, 5);
x.Print_Transpose(a, 20, 5);
}
}
i don't know how to make a class which sorta each row from smallest to largest and also i dont know how to create a class which finds the matrix's peak value.
You can run over the array, keeping the maxNum:
public int getMax(int[,] fromArray)
{
int maxNum = 0;
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
if (maxNum < fromArray[a,b])
{
maxNum = fromArray[a, b];
}
}
}
return maxNum;
}
Call the function like:
Console.Write("Max number = {0:D}", x.getMax (a));
If you want a sort method, you can place all values in a List, sort them and convert back to array.
public int[] SortArray(int[,] fromArray)
{
List<int> newList = new List<int>(fromArray.Length);
for (int b = 0; b < fromArray.GetUpperBound(1); b++)
{
for (int a = 0; a < fromArray.GetUpperBound(0); a++)
{
newList.Add (fromArray[a, b]);
}
}
newList.Sort();
return newList.ToArray<int>();
}

Convert String[*,*] into int[*,*] in C# winform application

Hello everyone I am new to programming in c#, what I am going to do is that I want to convert the 2D string array to 2D integer array, the reason for this conversion is that I want to pass that integer array to another method for some calculation. Thanks in advance for helping.
public void Matrix()
{
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
Random rnd = new Random();
int[,] matrixA = new int[a, b];
string matrixString = "";
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
matrixString += matrixA[i, j];
matrixString += " ";
}
matrixString += Environment.NewLine;
}
txtA.Text = matrixString;
txtA.TextAlign = HorizontalAlignment.Center;
}
Your code is actually pretty close. Try this:
private Random rnd = new Random();
public int[,] Matrix(int a, int b)
{
int[,] matrixA = new int[a, b];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
matrixA[i, j] = rnd.Next(1, 100);
}
}
return matrixA;
}
What you have there is a function that does not rely on any WinForms controls and will produce your int[,] quickly and efficiently.
Let the calling code work with the WinForms controls:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
Now you can pass the matrix to anything that requires an int[,].
If you need to display the matrix then create a separate function for that:
public string MatrixToString(int[,] matrix)
{
StringBuilder sb = new();
for (int i = 0; i < matrix.GetLength(0); i++)
{
string line = "";
for (int j = 0; j < matrix.GetLength(1); j++)
{
line += $"{matrix[i, j]} ";
}
sb.AppendLine(line.Trim());
}
return sb.ToString();
}
Your calling code would look like this:
int a = int.Parse(txtRowA.Text);
int b = int.Parse(txtColA.Text);
int[,] matrix = Matrix(a, b);
UseTheMatrix(matrix);
txtA.Text = MatrixToString(matrix);
txtA.TextAlign = HorizontalAlignment.Center;
A sample run produces:
You can use List as a helper to store the elements of the array extracted from the string, but first I replaced the SPACE between elements in your string with a special character '|' as a separator to make it easier to extract the numbers from the string.
you can do somthing like this:
public static int[,] ConvertToInt(string matrix)
{
List<List<int>> initial = new List<List<int>>();
int lineNumber = 0;
int currenctIndex = 0;
int lastIndex = 0;
int digitCount = 0;
initial.Add(new List<int>());
foreach (char myChar in matrix.ToCharArray())
{
if (myChar == '|')
{
initial[lineNumber].Add(int.Parse(matrix.Substring(lastIndex, digitCount)));
lastIndex = currenctIndex+1;
digitCount = 0;
}
else
digitCount++;
if (myChar == '\n')
{
lineNumber++;
if(currenctIndex < matrix.Length-1)
initial.Add(new List<int>());
}
currenctIndex++;
}
int[,] myInt = new int[initial.Count, initial[0].Count];
for (int i = 0; i < initial.Count; i++)
for (int j = 0; j < initial[i].Count; j++)
myInt[i, j] = initial[i][j];
return myInt;
}

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();
}
}
}

Average row values with same time in datagridview

I am writing this software which reads a CSV file and puts it into a datagridview.
Here you can see the picture of the application:
I am achieving this with the following code, firstly:
private string[,] LoadCsv(string filename)
{
string whole_file = System.IO.File.ReadAllText(filename);
whole_file = whole_file.Replace('\n', '\r');
string[] lines = whole_file.Split(new char[] { '\r' },
StringSplitOptions.RemoveEmptyEntries);
int num_rows = lines.Length;
int num_cols = lines[0].Split(';').Length;
string[,] values = new string[num_rows, num_cols];
for (int r = 0; r < num_rows; r++)
{
string[] line_r = lines[r].Split(';');
for (int c = 0; c < num_cols; c++)
{
values[r, c] = line_r[c];
}
}
return values;
}
and then this:
private void btnGo_Click(object sender, EventArgs e)
{
string[,] values = LoadCsv(txtFile.Text);
int num_rows = values.GetUpperBound(0) + 1;
int num_cols = values.GetUpperBound(1) + 1;
dgv.Columns.Clear();
for (int c = 0; c < num_cols; c++)
dgv.Columns.Add(values[0, c], values[0, c]);
for (int r = 1; r < num_rows; r++)
{
dgv.Rows.Add();
for (int c = 0; c < num_cols; c++)
{
dgv.Rows[r - 1].Cells[c].Value = values[r, c];
}
}
}
What I am asking now is if there is the possibility to average the values minute by minute inside the datagridview or with another interval of time (needs to be a low interval 1 to 5 minutes).
Thanks for your help!
If i understood you right you want to read the csv every x minutes again ?
Maybe you can use a timer like this
var timer = new System.Threading.Timer((e) =>
{
LoadCsv(string filename)
}, null, 0, TimeSpan.FromMinutes(5).TotalMilliseconds);

the Construction of and passing of parameters of a method that searches a 2-d array filled with random numbers

I am having problems with the last method of my program. I can't seem to figure out the right way to pass the parameters or maybe perhaps the way I have the method coded is wwrong. Please help! The stipulations of the method is below:
The SearchArray() method will return a bool to indicate if the number searched for was found or not. Its parameter is supposed to have: An integer that is the number to be searched for, a two-dimensional array to search, an out reference integer parameter that will represent the row index and an out reference integer parameter that will represent the column index
This method will use the first parameter and the two-dimensional array and will search the array for the number chosen by the GetNumber() method. I must Initialize the row and column parameters to -1. As the program goes through the array, if the number is found, assign the row and column parameters to the row and column index numbers where it is found and stop searching the array right away. The method is supposed to return a Boolean value to indicate whether or not the number was found.
Any help on this is greatly appreciated I have been on here for awhile trying to get this figured out completely right now if I run it it gets to the point where it asks for a number then runs into an error stating the index is outside the boundaries. Here is my code so far:
static void Main(string[] args)
{
int [,] randomNumArray = new int[3, 5];
FillArray(randomNumArray);
PrintArray(randomNumArray);
SumRows(randomNumArray);
SumCols(randomNumArray);
SumArray(randomNumArray);
int rows, cols;
int search = GetNumber();
SearchArray(search, randomNumArray, out rows, out cols);
}
public static void FillArray(int[,] randomNumbersArray)
{
Random num = new Random();
for (int r = 0; r < randomNumbersArray.GetLength(0); r++)
{
for (int c = 0; c < randomNumbersArray.GetLength(1); c++)
{
randomNumbersArray[r, c] = num.Next(15, 97);
}
}
}
public static void PrintArray(int[,] randomPrintArray)
{
for (int r = 0; r < randomPrintArray.GetLength(0); r++)
{
for (int c = 0; c < randomPrintArray.GetLength(1); c++)
{
Console.Write("{0,3:F0}", randomPrintArray[r, c]);
}
Console.WriteLine("");
}
Console.WriteLine("");
}
public static void SumRows(int[,] sumOfRowsArray)
{
int rowSum;
for (int r = 0; r < sumOfRowsArray.GetLength(0); r++)
{
rowSum = 0;
for (int c = 0; c < sumOfRowsArray.GetLength(1); c++)
{
rowSum += sumOfRowsArray[r, c];
}
Console.WriteLine("The total sum for row "+ (r + 1) + " is: " + rowSum + ".");
}
Console.WriteLine("");
}
public static void SumCols(int[,] sumOfColsArray)
{
int colsSum;
for (int c = 0; c < sumOfColsArray.GetLength(1); c++)
{
colsSum = 0;
for (int r = 0; r < sumOfColsArray.GetLength(0); r++)
{
colsSum += sumOfColsArray[r, c];
}
Console.WriteLine("The total sum for column " + (c + 1) + " is: " + colsSum + ".");
}
Console.WriteLine("");
}
public static void SumArray(int[,] sumOfAllArray)
{
int sumOfAll = 0;
for (int r = 0; r < sumOfAllArray.GetLength(0); r++)
{
for (int c = 0; c < sumOfAllArray.GetLength(1); c++)
{
sumOfAll += sumOfAllArray[r, c];
}
}
Console.WriteLine("Total for sum of the Array is: " + sumOfAll + "\n");
}
public static int GetNumber()
{
Console.Write("Please enter a number between 15 and 96: ");
int chosenNumber = int.Parse(Console.ReadLine());
while (chosenNumber > 96 || chosenNumber < 15)
{
Console.Write("Number not between 15 and 96. Try again: ");
chosenNumber = int.Parse(Console.ReadLine());
}
return chosenNumber;
}
public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)
{
rowIndex = -1;
colsIndex = -1;
for (int c = 0; c < searchableArray.GetLength(0); c++)
{
for (int r = 0; r < searchableArray.GetLength(1); r++)
{
if (searchableArray[r, c] == soughtOutNum)
{
rowIndex = r;
colsIndex = c;
return true;
break;
}
}
}
return false;
}
You can use LINQ for your SearchArray.
public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)
{
if(searchableArray.Any(x => soughtOutNum))
{
colsIndex = searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(0);
rowIndex= searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(1);
}
else
{
return false;
}
}
This returns your first hit's column and row.

Categories