Accepting a 'n x n' Matrix in C# - c#

I've been bugged with this idea for a while.
Accepting an array with spaces is not straight forward in c#. How do we accept a 2d array, whose size is given by the user? I tried this, but something isn't right. Help is much appreciated. Thank You.
Input:
4
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
Where the first line specifies the value of 'n' in 'n x n'
Well, the code i tried was this. This might look stupid for a few of you :
string input;
string[] inputArray;
int[] inputInt;
int MxM = Convert.ToInt32(Console.ReadLine()); //MxM = First Line=n
int[,] array = new int[MxM, MxM];
for (int i = 0; i < MxM; i++)
{
for (int j = 0; j < MxM; j++)
{
input = Console.ReadLine();
inputArray = input.Split(' ');
inputInt = new int[MxM];
for (int k = 0; k < MxM; k++)
{
inputInt[k] = int.Parse(inputArray[k]);
array[i, j] = inputInt[k];
}
}
}
Hopefully, the answer for this will also be the answer to output a matrix. Thank You

Either:
for (int i = 0; i < MxM; i++)
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(Console.ReadLine());
or:
for (int i = 0; i < MxM; i++)
{
inputArray = Console.ReadLine().Split(' ');
for (int j = 0; j < MxM; j++)
array[i, j] = Convert.ToInt32(inputArray[j]);
}
which, of course, could fail if you don't enter in the right format.

If I am understanding what you want correctly:
You would like to take an input N, in your example 4, with that - create a 4 x 4 array. Then for each index in the first dimension, ask the user for input equating to N number of integers separated by spaces. Read that input and place it into the array at the proper 2d-index. So with 4 as the first input, the user will be prompted something like:
Please input 4 integers(separated by spaces):
The user would type in, for example:
Please input 4 integers(separated by spaces): 1 2 3 4
And hit enter. Again the user is prompted:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces):
And so on until:
Please input 4 integers(separated by spaces): 1 2 3 4
Please input 4 integers(separated by spaces): 2 3 4 5
Please input 4 integers(separated by spaces): 3 4 5 6
Please input 4 integers(separated by spaces): 4 5 6 7
You could probably use something like the following in this case:
class Program
{
static void Main(string[] args)
{
int size;
Console.WriteLine("Please enter the size of the matrix:");
if (!int.TryParse(Console.ReadLine(), out size))
{
Console.WriteLine("The value provided for the size was not a proper integer value.");
Console.WriteLine("Press ESC to quit...");
while (Console.ReadKey().Key != ConsoleKey.Escape) { }
return;
}
int[,] matrix = new int[size, size];
for (int i = 0; i < size; ++i)
{
bool complete = false;
while (!complete)
{
Console.WriteLine(string.Format("[{0}] - Please input {1} integers(separated by spaces):", i, size));
string[] input = Console.ReadLine().Split(' ');
if (input.Count() != size)
{
Console.WriteLine("The input was invalid, try again...");
continue;
}
for (int j = 0; j < size; ++j)
{
if (!int.TryParse(input[j], out matrix[i, j]))
{
complete = false;
Console.WriteLine("The input was invalid, try again...");
break;
}
complete = true;
}
}
}
Console.WriteLine("Output: \n");
WriteMatrix(matrix, size);
Console.ReadKey();
}
private static void WriteMatrix(int[,] matrix, int size)
{
string output = string.Empty;
for(int i = 0; i < size; ++i)
{
string line = string.Empty;
for (int j = 0; j < size; ++j)
line += string.Format("{0} ", matrix[i, j]);
output += string.Format("{0}\n", line.Trim());
}
Console.WriteLine(output);
}
}
The code above should be mostly safe against the user typing invalid values, but you could probably spend some time to clean it up or enhance it some more. The basic idea is there.

You can try to use code like this:
Console.ReadLine().Split().Select(str => Convert.ToInt32(str)).ToArray()
to get an int array out of the line.
I think you understood the idea.

public static int[,] MatrixConstructor()
{
int N = Convert.ToInt32(Console.ReadLine());
int[,] matrix = new int[N, N];
for (int i = 0; i < N; i++)
{
String[] line = Console.ReadLine().Split(' ');
for (int j = 0; j < N; j++)
{
matrix[i,j] = Convert.ToInt32(line[j]);
}
}
return matrix;
}
This conforms to your input.

Related

input 2d array sideways

how can I input an integer array sideways not downward? suppose it has array [2,2] then in c # :
input :
1
2
3
4
I want to store like this:
1 2
3 4
what should i do? I am confused, as for the code I use:
int length = Convert.ToInt16(Console.ReadLine());
int[,] box = new int[length, 2];
for(int i = 0; i<length; i++){
for(int j = 0; j<2; j++){
photo[i, j] = Convert.ToInt16(Console.ReadLine());
}
}
static void Main(String[] args){
int length = Convert.ToInt32(Console.ReadLine());
int[,] box = new int[length, 2];
for (int i = 0; i < length; i++){
box[i, 0] = Int32.Parse(Console.ReadLine());
box[i, 1] = Int32.Parse(Console.ReadLine());
}
}
As you have mentioned that you have two columns it might give you a better understanding.For each row since we have two columns due to that I we are fetching values two times.

How would you create n nested loops for math?

So, I am trying to wrap my head around understanding how you can use a variable to denote how many times a loop is nested.
Here is an example I write up to simulate the output of dimensions = 4:
static void Main(string[] args)
{
int dimensions = 4; // e.g. for (1, 2, 3, 4), dimensions = 4
Console.WriteLine($"{addNumbers(dimensions)}");
Console.ReadKey();
}
static long addNumbers(int dimensions)
{
long number = 0;
// hard coded to be dimensions = 4
for (int h = 0; h <= dimensions; h++)
for (int i = 0; i <= dimensions; i++)
for (int j = 0; j <= dimensions; j++)
for (int k = 0; k <= dimensions; k++)
number += h + i + j + k; // just some random math
return number;
}
This will present the expected output of:
5000
So to readdress the problem, how can I code to allow this for n dimensions? Thanks for your help!
For arbitrary n dimensions you can loop with a help of array int[] address which represents n dimensions:
static long addNumbers(int dimensions) {
int[] address = new int[dimensions];
// size of each dimension; not necessary equals to dimensions
// + 1 : in your code, int the loops you have i <= dimensions, j <= dimensions etc.
int size = dimensions + 1;
long number = 0;
do {
//TODO: some math here
// i == address[0]; j = address[1]; ... etc.
number += address.Sum();
// next address: adding 1 to array
for (int i = 0; i < address.Length; ++i) {
if (address[i] >= size - 1)
address[i] = 0;
else {
address[i] += 1;
break;
}
}
}
while (!address.All(index => index == 0)); // all 0 address - items're exhausted
return number;
}
Finally, let's add some Linq to look at the results:
int upTo = 5;
string report = string.Join(Environment.NewLine, Enumerable
.Range(1, upTo)
.Select(i => $"{i} -> {addNumbers(i),6}"));
Console.Write(report);
Outcome:
1 -> 1
2 -> 18
3 -> 288
4 -> 5000 // <- We've got it: 5000 for 4 dimensions
5 -> 97200

Please help in simple pattern program in c#

I want to print the following pattern:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
But I am getting the following output:-
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Here is the Code:
static void Main(string[] args)
{
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i<=n; i++)
{
for (int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ",num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
}
What I am doing wrong with the spaces? I am unable to do it.
This will do the trick
int spacelimit = 13, num = 1, n = 5;
for(int i = 1; i <= n; i++)
{
for(int space = spacelimit; space >= i; space--)
{
Console.Write(" ");
}
for(int k = 1; k <= i; k++)
{
Console.Write("{0,2:D} ", num++);
}
spacelimit = spacelimit - 2;
Console.WriteLine();
}
Console.ReadKey();
I have just changed 3 to 2 i.e. spacelimit - 2 and {0,2:D}
Yes changing spacelimit also solves the issue with trailing spaces but this solution worked as expected ... please have a look on the image.
If we make space>= i-3 in for loop, as shown below, it works fine. Please check. Thanks.
int spacelimit = 13, num = 1, n = 5;
for (int i = 1; i <= n; i++)
{
for (int space = spacelimit; space >= i - 3; space--) // HERE, I MADE i-3
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write("{0,3:D} ", num++);
}
spacelimit = spacelimit - 3;
Console.WriteLine();
}
Console.ReadKey();
Set the initial value of spacelimit to 16.

Printing a 2D-array into "squares"

I'm trying to learn how to work with 2D-array and I can't seem to understand how to print them correctly. I want to print them in a "square" like 5x5 but all I get is one line. I've tried both WriteLine and Write and changed some of the variables in the loops but I get either an error or not the result I want to have. The code is supposed to print out a 5x5 with a random sequence of 15 numbers in each column. I get the correct numbers out of it, it's only the layout that is wrong.
static void Main(string[] args)
{
Random rnd = new Random();
int[,] bricka = new int[5, 5];
int num = 0;
int num1 = 1;
for (int i = 0; i < bricka.GetLength(1); i++)
{
num += 16;
for (int j = 0; j < bricka.GetLength(0); j++)
{
bricka[j, i] = rnd.Next(num1, num);
}
num1 += 16;
}
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
}
Console.ReadKey();
}
This is my print, I would like to have the the 12 under the 8 and 14 under the 12 and so on.
http://i.imgur.com/tfyRxf1.png
You need to call WriteLine() after each line, so that each line is printed on a separate line:
for (int i = 0; i < bricka.GetLength(0); i++)
{
for (int j = 0; j < bricka.GetLength(1); j++)
{
Console.Write(bricka[i, j]+ " " );
}
Console.WriteLine();
}
That would be one way of doing it, anyway.

Output to the screen without moving to a new line

Console.WriteLine automatically move text on a new line and I have output on the console like:
1
2
3
4
5
..
But I need:
1234
5..
Code:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
Console.WriteLine(aField[i, j]);
Console.WriteLine();
}
If you don't want to write a line, don't use Console.Write*Line*. Just use Console.Write:
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(aField[i, j]);
}
Console.WriteLine();
}
(Note that your sample output only contains four characters, whereas your inner loop has 5 iterations. I'm hoping this is just a sample discrepancy, and nothing more complicated.)

Categories

Resources