How to extract specific column from 2D array - c#

I have an array and i want to extract specific column from it, let's say the 3rd column only.
Example:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
What is want is to extract 3rd column and display only:
3
3
3
3
This is my code where i am able to create a dynamic array specified by the user:
int r;
int c;
Console.Write("Enter number of rows: ");
r = (int)Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number of columns: ");
c = (int)Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[r, c];
/*Insert Values into Main Matrix
--------------------------------------------------------------------------------*/
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
Console.Write("Enter value for matrix[{0},{1}] = ",row, col);
matrix[row, col] = (int)Convert.ToInt32(Console.ReadLine());
}
}
/*Print and show initial Matrix
--------------------------------------------------------------------------------*/
Console.WriteLine("Your matrix is,");
for (int row = 0; row < r; row++)
{
for (int col = 0; col < c; col++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
/*Fixing first 2 columns
--------------------------------------------------------------------------------*/
int startingMatrixCols = 2;
Console.WriteLine("Fixed first 2 columns:");
for (int row = 0; row < r; row++)
{
for (int col = 0; col < startingMatrixCols; col++)
{
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}

var column = 2; // your expected column
//if it needs to be dynamic, you can read it from user entry
// Console.Write("Enter expected column: ");
// column = int.Parse(Console.ReadLine()); //enhance with error checks
for (int row = 0; row < r; row++)
{
Console.Write(matrix[row, column] + " ");
}

Console.Write("Enter the column number to display ");
int displayColNo = (int)Convert.ToInt32(Console.ReadLine());
/*If displayColNo=3 it displays only 3rd column numbers*/
for (int row = 0; row < r; row++)
{
Console.Write(matrix[row, displayColNo]);
Console.WriteLine();
}

Related

Get the specific whole (0) dimension in multidimensional array (C# UNITY)

How can I possibly count only the specific whole column I want in a multidimensional array
I do the counting of my whole column and row like this
//COLUMN
for(int col = 0; col < table.GetLength(0); col++)
{
int sum = 0;
//ROW
for (int row = 0; row < table.GetLength(1); row++)
{
if (table[col,row] != null)
{
sum++;
}
}
Debug.Log("table column: " + col + " has " + sum + " data");
}
What I want is just to get the specific whole Column then move to another Column just like that. I need to do this because i need to compare it with the last column value to the next one.
For example : I want to check how many data are there in the 2nd column then compare it with the 1st column.
You´re almost there. All you have to do is store the sum of the current column into a list:
var List<int> sums = new List<int>();
//COLUMN
for(int col = 0; col < table.GetLength(0); col++)
{
int sum = 0;
//ROW
for (int row = 0; row < table.GetLength(1); row++)
{
if (table[col,row] != null)
{
sum++;
}
}
Debug.Log("table column: " + col + " has " + sum + " data");
sums.Add(sum);
}
Now you can easily compare the number of rows in colum 1 and that of column 2:
bool areEqual = sums[0] == sums[1];
Got a solution :)
//generic function
public static int CountRow<T>(T[,] table, int col)
{
if (table == null || col < 0 || col >= table.GetLength(1))
{
//handle error
return -1;
}
//this is the same as the block of the outer for loop
int sum = 0;
for (int row = 0; row < table.GetLength(1); row++)
{
if(table[col,row] != null)
{
sum++;
}
}
return sum;
}
then used it like this
int prevSum = -1;
for (int col = 0; col < table.GetLength(0); ++col)
{
int sum = CountRow(table, col);
Debug.Log("table column :" + col + " has " + sum + " data");
if (sum == prevSum)
{
//comparison happens
}
}

Transpose non square matrices C#

I can transpose a square matrix, but now I'd like to transpose a non square matrix (in my code 3*2) with user input.
Other sources recommended me to create a new matrix first, which I have done. I manage to make the matrix, but when transposing, it stops from the 4th value.
I have looked at other topics but I can't find the error. Here is my code so far, can someone tell me where I went wrong?
Thanks!
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write("Enter num: ");
matrix1[i, j] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
Console.Write(matrix1[i, j] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
matrix2[j, i] = matrix1[j, i];
Console.Write(matrix2[j, i] + " ");
}
Console.WriteLine(" ");
}
This is what I get when running the program:
//output
Enter num: 1
Enter num: 2
Enter num: 3
Enter num: 4
Enter num: 5
Enter num: 6
first matrix:
1 2
3 4
5 6
transposed matrix:
1 3
2 4
//--->> Only went up to 4th value?
So, at the beginning you load a matrix with fields : "i,j" => "row, column"
On the last step, you try accessing the matrix with a "j,i" => "column, row" order.
You're inverting the i,j indexes.-
Let me help you by just changing the variable names :
//const
const int ROWS = 3;
const int COLS = 2;
//first matrix
int[,] matrix1 = new int[ROWS, COLS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column ++)
{
Console.Write("Enter num: ");
matrix1[row, column] = int.Parse(Console.ReadLine());
}
}
//output
Console.WriteLine("Eerste matrix: ");
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{`enter code here`
Console.Write(matrix1[row, column] + " ");
}
Console.WriteLine(" ");
}
//transposed matrix
Console.WriteLine("Tweede matrix: ");
int[,] matrix2 = new int[COLS, ROWS];
for (int row = 0; row < ROWS; row++)
{
for (int column = 0; column < COLS; column++)
{
matrix2[column, row] = matrix1[row, column];
Console.Write(matrix2[column, row] + " ");
}
Console.WriteLine(" ");
}
// EDIT : actually noticed the sample didn't traspose it properly. fixed it.
Replace
matrix2[j, i] = matrix1[j, i];
with
matrix2[j, i] = matrix1[i, j];
This way a row number of matrix1 becomes a column number for matrix2 - i.e. the matrix gets transposed.
If you combine the other two answers, you will have a complete picture:
This line is wrong and will give you an IndexOutOfRangeException:
matrix2[j, i] = matrix1[j, i];
In order to transpose you need to flip the indices:
matrix2[j, i] = matrix1[i, j];
Another problem is that when you print the matrix, you switch rows and columns.
It's easier to just extract the code for each functionality into a separate method.
Also, using the names i and j can be confusing. They look alike and they don't convey their meaning. When working with matrices, I like to use r and c (or row and column)
void PrintMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
Console.Write(m[r, c] + " ");
}
Console.WriteLine();
}
}
int[,] TransposeMatrix(int[,] m)
{
int rows = m.GetLength(0);
int columns = m.GetLength(1);
int[,] transposed = new int[columns, rows];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
transposed[c, r] = m[r, c];
}
}
return transposed;
}
Then the last part of your code becomes simply:
PrintMatrix(matrix1);
Console.WriteLine();
int[,] matrix2 = TransposeMatrix(matrix1);
PrintMatrix(matrix2);

'For' Loop being skipped?

I'm relatively new to programming, and I'm currently trying to get to grips with C#. I've reached a point where I'm learning about 'for' loops. The problem I'm stuck on is to create the shape below using only 'for' loops and the character '*' only once.
*
***
*****
*******
*********
The code I've written is below:
for (int row = 0; row < 5; row++)
{
for (int column = 0; column + row < 4; column++)
{
Console.Write(" ");
}
for (int column = 0; column + row >= 4; column++)
{
if (column - row >= 5)
break;
Console.Write("*");
}
Console.WriteLine();
}
From what I can see, the second nested 'for' loop is being skipped until the first loop is complete.
Replacing the spaces with "O", this displays the following:
OOOO
OOO
OO
O
*********
**********
***********
************
*************
**************
Can anyone see where I'm going wrong?
The problem is in the loop condition for the second nested loop, column + row >= 4. Since column starts at zero, the first execution is basically the same as row >= 4 so for any row < 5 it won't print, which is exactly the conditions of the first loop. This means all the spaces are printed, and then a bunch of stars.
You also don't need the if-statement since that is basically a second loop condition. Something like for (int column = 0; column <= row * 2; column++) would make the most sense.
You also should probably re-evaluate the outer loop, since you only want 5 lines, and you will go through 10 lines as-is.
for (int row = 0; row < 5; row++)
{
for (int column = 0; column + row < 4; column++)
{
Console.Write(" ");
}
for (int column = 0; column <= row * 2; column++)
{
Console.Write("*");
}
Console.WriteLine();
}
for (int row = 0; row < 10; row++)
{
// This code will only get run for the first 3 rows
for (int column = 0; column + row < 4; column++)
{
Console.Write(" ");
}
// This code will only get run for rows 4 and greater
for (int column = 0; column + row >= 4; column++)
{
if (column - row >= 5)
break;
Console.Write("*");
}
Console.WriteLine();
}
What you need to do is ensure your are putting the correct number of spaces followed by the correct number of * for each line.
Hint: You probably only want 5 rows not 10
This works:
for (int row = 0; row < 5; row++)
{
for (int column = 0; column < 5 + row + 1; column++)
Console.Write(column < 5 - row ? " " : "*");
Console.WriteLine();
}
*
***
*****
*******
*********
Worked out a solution:
for (int row = 0; row < 5; row++)
{
for (int column = 0; column + row < 4; column++)
{
Console.Write(" ");
}
for (int column = 0; column + row >= 0; column++)
{
if (column == (row * 2) + 1)
break;
Console.Write("*");
}
Console.WriteLine();
}
x...'s solution is probably more appropriate, being clearer and without the need for an if statement and any breaks, but you all helped me reach the answer without too much hand holding, and I appreciate that.
Thanks :D
A simple logic can be like this.
for(i=0 to 4) //since five rows
for(j=0 to 2*i-1) // is in multiple of 1, 3, 5
print(*)

How to get average of columns in a 2d array

I have just started using 2D arrays, but can't seem to figure out how to get the average of each column. I am using a for loop to have the user enter the data( a students grade), then a for loop to display the information user entered. But after the information is displayed, I want to display the average of each column. What should I do get the average of each column?
This is the code I have so far
static void Main(string[] args)
{
double[,] grades = new double[2, 3];
double result;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("Enter Grade " + (j + 1) + " For Group" + (i + 1) + ": ==>> ");
if (double.TryParse(Console.ReadLine(), out result)) grades[i, j] = result;
else
{
Console.WriteLine("*** INVALID GRADE ENTERED. PLEASE REENTER.");
}
}
}
for (int row = 0; row < 1; row++)
{
Console.WriteLine();
Console.Write(" Group " + (row + 1) + ": ");
Console.WriteLine(" Group " + (row + 2) + ": ");
Console.Write("=========== ===========");
for (int col = 0; col < 3; col++)
{
//String.Format("{0,-10} | {1,-10} | {2,5}",
//make pring for execise 2 Console.Write(string.Format("{0,-5}", grades[row, col]));
Console.WriteLine();
Console.Write(string.Format("{0,-9}", ""));
Console.Write(string.Format("{0,-20}",grades[0, col]));
Console.Write(grades[1,col]);
}
Console.WriteLine();
Console.WriteLine("=========== ===========");
}
Console.WriteLine("\n\npress any key to exit...");
Console.ReadKey();
//print it for exercise 1 myArr[o, column]; myArr[ , column]
}`
If you are looking for a special command that will do it for you, you're out of luck! You'll just have to write the code to do it, the same way you would normally average a series of numbers. Hint: The number of elements in the 'y' dimension of a 2D array is given by e.g. grades.GetLength(1).
To get Average per columns you need to traverse columns for a fixed row and add their values like this:
int columnTotal, average;
for (int row = 0; row < 2; row++)
{
columnTotal = 0;
for (int col = 0; col < 2; col++)
{
columnTotal += grades[row, col];
}
average = columnTotal/2;
Console.WriteLine("Average: {0}", average);
}

Dynamically changing top border line C#

So I'm building a multiplication table for my C# class. I've got the code for the table complete, and it works as advertised. The issue is that I need a dynamically changing top border, because the table is as wide as the number the user enters for the width digit, at 5 character spacing. Any thoughts?
static void Main(string[] args)
{
int width, height;
//int tableWidth;
Console.Write("How wide do we want the multiplication table? ");
width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
height = Convert.ToInt32(Console.ReadLine());
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
}
I assume tableWidth needs to be calculated, and then a Console.Write("_") equal to the width of the total table. Thanks in advance for your help :)
You need to use another loop, like this:
Console.Write("How wide do we want the multiplication table? ");
int width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int height = Convert.ToInt32(Console.ReadLine());
Console.Write(" ");
for (int i = 0; i < width; i++)
Console.Write("_____");
Console.WriteLine("__");
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
You basically want to multiply the width by the padding you have given (5). Something like this will work. Keep in mind that I think you should break some of the spacing out into variables because you are re-using constant values like 5 in many places. Also the spacing before the x and the pipe should probably be a string variable, otherwise it is hard to see how many spaces go into each one. Here is my solution keeping the code in the same format you have so far:
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
Console.Write(" |");
for (int x = 1; x <= (width * 5); x++)
Console.Write("-");
Console.WriteLine();
Making the whole method:
static void Main(string[] args)
{
int width, height;
//int tableWidth;
Console.Write("How wide do we want the multiplication table? ");
width = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
height = Convert.ToInt32(Console.ReadLine());
Console.Write(" x|");
for (int x = 1; x <= width; x++)
Console.Write("{0, 5}", x);
Console.WriteLine();
Console.Write(" |");
for (int x = 1; x <= (width * 5); x++)
Console.Write("-");
Console.WriteLine();
for (int row = 1; row <= height; row++)
{
Console.Write("{0, 5}|", row);
for (int column = 1; column <= height; ++column)
{
Console.Write("{0, 5}", row * column);
}
Console.WriteLine();
}
Console.ReadLine();
}
Here is your code with improved naming and top line drawing (btw you have incorrect rows displaying - you are iterating over rows instead of columns in second loop):
const int columnWidth = 5;
string cellFormat = "{0, " + columnWidth + "}";
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
for (int row = 1; row <= rowsCount; row++)
{
Console.Write(cellFormat + "|", row);
for (int column = 1; column <= columnsCount; column++)
Console.Write(cellFormat, row * column);
Console.WriteLine();
}
Next refactoring step is extracting classes and methods:
Console.Write("How wide do we want the multiplication table? ");
int columnsCount = Convert.ToInt32(Console.ReadLine());
Console.Write("How high do we want the multiplication table? ");
int rowsCount = Convert.ToInt32(Console.ReadLine());
MultiplicationTable table = new MultiplicationTable(columnsCount, rowsCount);
table.Draw();
Now code is more clear - it tells that you have multiplication table, and you want to draw it. Drawing is simple - you draw column headers and raws:
public class MultiplicationTable
{
private const int columnWidth = 5;
private string cellFormat = "{0, " + columnWidth + "}";
private int columnsCount;
private int rowsCount;
public MultiplicationTable(int columnsCount, int rowsCount)
{
this.columnsCount = columnsCount;
this.rowsCount = rowsCount;
}
public void Draw()
{
DrawColumnHeaders();
DrawRaws();
}
private void DrawColumnHeaders()
{
string title = String.Format(cellFormat + "|", "x");
Console.Write(title);
for (int i = 1; i <= columnsCount; i++)
Console.Write(cellFormat, i);
Console.WriteLine();
int tableWidth = columnWidth * columnsCount + title.Length;
Console.WriteLine(new String('-', tableWidth));
}
private void DrawRaws()
{
for (int rowIndex = 1; rowIndex <= rowsCount; rowIndex++)
DrawRaw(rowIndex);
}
private void DrawRaw(int rowIndex)
{
DrawRawHeader(rowIndex);
for (int columnIndex = 1; columnIndex <= columnsCount; columnIndex++)
DrawCell(rowIndex * columnIndex);
Console.WriteLine();
}
private void DrawRawHeader(int rowIndex)
{
Console.Write(cellFormat + "|", rowIndex);
}
private void DrawCell(int value)
{
Console.Write(cellFormat, value);
}
}

Categories

Resources