How to print matrix? - c#

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.

Related

How to print below Star pattern

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

How to set a maximum value of string that can be shown in a matrix?

I'm trying to make a matrix that will show the string s only if it it displays a number less than 10. It would probably be easier doing this with an integer instead of the string but it doesn't show the same 8x8(or any other combination) the same because the "string.Empty" seems to be being the key(if someone could explain that part too, it would help me).
I also want to know how to display lets say letter "a" in the whole matrix, so that if the matrix is 3x3 I see 3 "a" in 3 rows.
Code here shows me matrix which lets s go over 10 which makes it not looking like a square.
string s = "";
int[,] matrix = new int[8, 8];
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
s += matrix[i, j] = i + j;
}
Console.WriteLine(s);
s = string.Empty;
}

c# Print rows from array that only contain positive integers

I'm really close ,but I just can't seem to wrap my head around the last step.
So what I want is to have 2d matrix and print only the rows that have ALL positive ints.
Right now my code is just taking out the ints that are either 0 or negative,but I need to remove the entire line if said line contains a 0 or negative.
This is what I'm getting right now
Input:
1 2 6 4
1 5 0 9
Output:
1 2 6 4
1 5
So basically it should not have printed the 2nd row b/c it had a non positive integer
What am I doing wrong?
I appreciate you taking the time to give this a look over!
static void Main(string[] args)
{
// reads in multiples lines( array from console)
List<string> L = readAllLines();
// feeds read lines into matrix
int[,] m = convertListToIntMatrix(L);// feeds read lines into matrix
int Rows = m.GetLength(0);
int Cols = m.GetLength(1);
for (int r = 0; r < Rows; r++)
{
for (int c = 0; c < Cols; c++)
{
if (m[r, c] <= 0)
{
break;
}
else Console.Write("{0} ", m[r, c]);
}
Console.WriteLine();
}
Change your loop to something like this:
for (int r = 0; r < Rows; r++)
{
bool rowOkay = true;
for (int c = 0; c < Cols; c++)
{
if (m[r, c] <= 0)
{
rowOkay = false;
}
}
if (rowOkay)
{
for(int i=0;i<Cols;++i) {Console.Write("{0} ", m[r,i]);}
Console.WriteLine();
}
}
You break when you find the 0 but you output everything before. Instead you could set a flag and later evaluate it to output the row if the flag is not set. You would still break but defer all output until you know the row is good.
Are you in Jim Harris' PP2 class by any chance? You could also set a variable to count how many positive numbers there were in the row and if it equals the number or integers in the row then print the row out.
if you are using list collection, just check Min() value of the list;
list1.Min() <= 0

C# check given word to answer word

I'm making a simple spell checker for C#, I want to try and compare a given answer to the randomly chosen word.
I want to compare the first letter to all the letters given in the answer so I can tell if it's correct, it's there was a swap of letters, a deletion or an added letter. I would ultimately like to be able to tell if only one letter was wrong to see a substitution was used.
For example, correct answer hello:
checking first letter ~H
h e l l o
1 0 0 0 0
h h e l l o
1 1 0 0 0 0
e l l o
0 0 0 0
Then go through it for the second letter.
I've absolutely no idea when it comes to C#.
I've tried
int CheckErrors(string Answer, string Guess)
{
if (Answer == Guess)
{
return 1;
}
if (Answer == null || Guess == null)
{
return -1;
}
for (int i = 0; i <= Answer.Length; i++)
{
if (Guess[i] != Answer[i])
{
count++;
//substitution = -4
//deletion = -5
//transposition = -6
//insertion = -7
}
return count;
}
return -9;
}
but I just can't get any further.
UPDATE:
with further research I guess what I was trying to do is something like:
STRING answer = answer_given
STRING input = correct_answer
int check = 0;
FOR (int i = 0; i < input.Length; i++)
{
FOR (int ii = 0; ii < answer.Length; ii++)
{
if (input[i] == answer[i])
{
int check++;
}
}
}
Obviously I know this would keep adding check up, but I can't guess what how else to do it.
ANOTHER UPDATE!
I can use this-
int CheckErrors(string Answer, string Guess)
{
int[,] d = new int[Answer.Length + 1, Guess.Length + 1];
for (int i = 0; i <= Answer.Length; i++)
d[i, 0] = i;
for (int j = 0; j <= Guess.Length; j++)
d[0, j] = j;
for (int j = 1; j <= Guess.Length; j++)
for (int i = 1; i <= Answer.Length; i++)
if (Answer[i - 1] == Guess[j - 1])
d[i, j] = d[i - 1, j - 1]; //no operation
else
d[i, j] = Math.Min(Math.Min(
d[i - 1, j] + 1, //a deletion
d[i, j - 1] + 1), //an insertion
d[i - 1, j - 1] + 1 //a substitution
);
return d[Answer.Length, Guess.Length];
}
But I need a way to do a count for the amount of times each error is used?
Several issues with your function:
You're trying to use a single return value to handle multiple scenarios in which the meaning of that value is not consistent. It's not advisable for a function to be able to return both a state (match, one or both values null, no match, etc) and a counter.
If you're going to use numbers to represent return states, use enum to make it more readable.
Your for loop always terminates after one iteration because it hits the return statement every time. Your return statement needs to be moved after the for loop.
if (Guess[i] != Answer[i]) will throw an exception if i is greater than the length of Guess.
It's not clear what count is supposed to represent, and it's not defined in the function.
You need to better define what exactly is your function supposed to do. If answer is "Hello" and guess is "Hhello", what are you returning? The number of letters that don't match (1)? A code that represents what the error was (Insertion)? Where the error is located? If you need more than one of those things, then you need a separate function.
You may get inspiration by looking at Approximate String Matching in Wikipedia and StackOverflow.
Have you considered trying string.Compare(...)?
http://msdn.microsoft.com/en-us/library/zkcaxw5y.aspx

find diagonal in 2 dimensional array

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

Categories