Printing entire array in C# - c#

I have a simple 2D array:
int[,] m = { {0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} };
How can I print this out onto a text file or something? I want to print the entire array onto a file, not just the contents. For example, I don't want a bunch of zeroes all in a row: I want to see the
{{0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0} };
in it.

Just iterate over it and produce the output. Something like
static string ArrayToString<T>(T[,] array)
{
StringBuilder builder = new StringBuilder("{");
for (int i = 0; i < array.GetLength(0); i++)
{
if (i != 0) builder.Append(",");
builder.Append("{");
for (int j = 0; j < array.GetLength(1); j++)
{
if (j != 0) builder.Append(",");
builder.Append(array[i, j]);
}
builder.Append("}");
}
builder.Append("}");
return builder.ToString();
}

There is no standard way to get those { brackets, you have to put them through the code while iterating through your array and writing them to the file

Related

how to print the row of a matrix(multi-dimensional array) in a new line

I have a multi-dimensional array in C#, I have assigned the indices of the matrices by capturing input from a user, I am trying to implement a conditional structure that will let me print the rows of my matrix each on a separate line, for example if my array is A and A has a dimension of 3 by 3 then the code prints the first three elements on the first line, the next three elements on the next line and so on and so forth. I am trying to achieve this because it will be easier to understand the structure as a normal matrix and also build an entire matrix class with miscallenous operations.
Code
class Matrix{
static int[,] matrixA;
static void Main(string[] args){
Console.WriteLine("Enter the order of the matrix");
int n = Int32.Parse(Console.ReadLine());
matrixA = new int[n, n];
//assigning the matrix with values from the user
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
matrixA[i, j] = Int32.Parse(Console.ReadLine());
}
}
//the code below tries to implement a line break after each row for the matrix
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if( (n-1-i) == 0)
{
Console.Write("\n");
}
else
{
Console.Write(matrixA[i, j].ToString() + " ");
}
}
}
}
}
How do I modify my code so that if the array has 9 elements and its a square matrix then each row with three elements are printed on a single line.
I would use something like this for the output:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(matrixA[i, j].ToString() + " ");
}
Console.Write("\n");
}
When the inner loop is done, that means one row has been completely printed. So that's the only time the newline is needed. (n passes of the outer loop ==> n newlines printed).

How to shrink int array basing on the number of elements?

So let's say I have a base int[] tab array with 100 elements. I want to perform Erastotenes' Sieve using tmp array storing not compatibile elements. Since I don't know exactly how many elements will land in this array, I declare it as new int[100]. But is there any way to shrink that array after performing population task? Like for example, I end up with 46 numbers instead of 100, so I'd like to shrink that array's size accordingly, based on the number of said elements. I'd like to avoid manual resize, I'd rather do it programatically.
Sample code:
int[] tab = new int[100];
int[] tmp = new int[100];
for(int i = 0; i < tab.Length; i++) {
tab[i] = i;
}
EDIT. One idea that came to my mind is to perform while loop strictly counting amount of elements in tmp array which could help me determine its final size.
EDIT 2. Working solution:
int[] tab = new int[100];
List<int> tmp = new List<int>();
List<int> se = new List<int>();
for(int i = 0; i < tab.Length; i++)
{
tab[i] = i + 2;
}
se.Add(tab[0]);
se.Add(tab[1]);
for (int i = 2; i < tab.Length; i++)
{
if (tab[i] % 2 == 0 || tab[i] % 3 == 0)
{
if (tmp.IndexOf(tab[i]) == -1)
{
tmp.Add(tab[i]);
}
}
}
int k = 3;
int value;
while(k < tab.Length)
{
if(tmp.IndexOf(tab[k]) == -1) {
value = tab[k];
for (int i = k; i < tab.Length; i++)
{
if(tmp.IndexOf(tab[i]) == -1)
{
if(tab[i] % value == 0 && tab[i] != value)
{
tmp.Add(tab[i]);
}
else
{
if(se.IndexOf(tab[i]) == -1)
{
se.Add(tab[i]);
}
}
}
}
}
k++;
}
Console.WriteLine("Zawartość tablicy początkowej:");
for(int i = 0; i < tab.Length; i++)
{
Console.Write(tab[i] + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Elementy wykluczone:");
foreach(int t in tmp)
{
Console.Write(t + " ");
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Sito Erastotenesa:");
foreach (int s in se)
{
Console.Write(s + " ");
}
Console.WriteLine();
Console.WriteLine();
No, you can't shrink an array (or grow, for that matter). You can create a new array with the correct size and copy the data to the new one, but an array, once created, can not change size.
The easiest way to achieve this is using List<T> which is nothing more than a thin wrapper over an array that hides away all the plumbing of how and when the underlying array needs to grow and copying data from the "depleted" to the newer array.
Once you've populated the list, if you need an array then simply call ToArray().
public static void Resize<T> (ref T[]? array, int newSize);
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replace the old array with the new one. the array must be a one-dimensional array.
Changes the number of elements of a one-dimensional array to the specified new size.
You can read the full article here

How to make a Jagged Array?

Thinking like a simple array:
Console.WriteLine("Number: ");
int x = Convert.ToInt32(Console.ReadLine());
string[] strA = new string[x];
strA[0] = "Hello";
strA[1] = "World";
for(int i = 0;i < x;i++)
{
Console.WriteLine(strA[i]);
}
Now, how can I do it with a double array?
I've already tried this:
Console.WriteLine("Number 1: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number 2: ");
int y = Convert.ToInt32(Console.ReadLine());
// Got an error, right way string[x][];
// But how can I define the second array?
string[][] strA = new string[x][y];
strA[0][0] = "Hello";
strA[0][1] = "World";
strA[1][0] = "Thanks";
strA[1][1] = "Guys";
for(int i = 0;i < x;i++)
{
for(int j = 0;i < y;i++)
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}
}
If's there's a simpler way of doing this, i'll be happy to learn it.
It's only for knowledge, I'm studying double array for the first time, so have patience please :)
Here's my example:
https://dotnetfiddle.net/PQblXH
You are working with jagged array (i.e. array of array string[][]), not 2D one (which is string[,])
If you want to hardcode:
string[][] strA = new string[][] { // array of array
new string[] {"Hello", "World"}, // 1st line
new string[] {"Thanks", "Guys"}, // 2nd line
};
in case you want to provide x and y:
string[][] strA = Enumerable
.Range(0, y) // y lines
.Select(line => new string[x]) // each line - array of x items
.ToArray();
Finally, if we want to initialize strA without Linq but good all for loop (unlike 2d array, jagged array can contain inner arrays of different lengths):
// strA is array of size "y" os string arrays (i.e. we have "y" lines)
string[][] strA = new string[y][];
// each array within strA
for (int i = 0; i < y; ++i)
strA[i] = new string[x]; // is an array of size "x" (each line of "x" items)
Edit: Let's print out jagged array line after line:
Good old for loops
for (int i = 0; i < strA.Length; ++i) {
Console.WriteLine();
// please, note that each line can have its own length
string[] line = strA[i];
for (int j = 0; j < line.Length; ++j) {
Console.Write(line[j]); // or strA[i][j]
Console.Write(' '); // delimiter, let it be space
}
}
Compact code:
Console.Write(string.Join(Environment.newLine, strA
.Select(line => string.Join(" ", line))));
You're using a jagged array instead of a multidimensional one. Simply use [,] instead of [][]. You can then use it with new string[x, y].
First you need to clarify thing in your head before writing code.
I will recommend writing in simple phrase what you want to do. The code in your fiddle go into every direction. I will address the code in the fiddle and not your questionas you have typo error and other issue that where not present in the fiddle while the fiddle has error that the question do not have.
To simplify the problem lets use clear understandable names. The 2d array will be an table, with rows and columns.
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of columns:");
var y = int.Parse(Console.ReadLine());
var table = new string[x, y];
You need to to declare your table before knowing its size.
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row, col] = Console.ReadLine();
}
}
table.GetLength(0) is equivalent to X, and table.GetLength(1) is equivalent to Y, and can be replace.
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.GetLength(0); row++)
{
for (int col = 0; col < table.GetLength(1); col++)
{
Console.Write(table[row, col]);
}
Console.Write("\n");
}
For a 3x3 table with 00X, 0X0, X00 as inputs the result is
00X
0X0
X00
It works. You separate each cell when we display by simply adding a comma or a space.
Fiddle
And for Jagged Array:
// 1/. Ask for 2table dim sizes.
Console.WriteLine("Enter number of rows:");
var x = int.Parse(Console.ReadLine());
var table = new string[x][];
// 2/. Fill the board
for (int row = 0; row < table.GetLength(0); row++)
{
Console.WriteLine($"Enter of the line n°{row}");
var lineSize = int.Parse(Console.ReadLine());
table[row] = new string[lineSize];
for (int col = 0; col < table[row].Length; col++)
{
Console.WriteLine($"Enter the value of the cell [{row},{col}]");
table[row][col] = Console.ReadLine();
}
Console.Write("\n");
}
// 3/. Display the Table
Console.Write("\n");
for (int row = 0; row < table.Length; row++)
{
for (int col = 0; col < table[row].Length; col++)
{
Console.Write(table[row][col]);
}
Console.Write("\n");
}
Wrong variable in use:
for(int j = 0;i < y;i++) <- Should be j
{
// How can I see the items?
Console.WriteLine(strA[i][j]);
}

How to get the value of a two dimensional array in Razor?

I have a jagged array as shown below, and the array is inside a c# code:
#{
int[][] array = new int[2][4];
// codes here that manipulates the values of the array.
}
Now I want to get/traverse to the values in the array. But the code below just don't work. When I run the program I got a run-time error "Index was outside the bounds of the array."
for(var i = 0 ; i < #array.Count(); i++){
alert( '#array['i'].Length');
}
How to do that?
Thanks
try something like
foreach(var subArray in array)
{
#:alert(subArray.Length);
}
but wont the length always be the same since it is statically declared?
Traversing multidimension array:
int[,] a = new int[,]
{
{2, 4}
};
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
for (int k = 0; k <= a.GetUpperBound(1); k++)
{
// a[i, k];
}
}
The only problem I can see there is that the razor itself is a bit... odd; it is not clear whether the alert is intended to be cshtml or output, but the line does not look valid for either.
If alert is output, can you try:
// note this might need to be #for, depending on the line immediately before
for(var i = 0 ; i < array.Length; i++) {
#:alert('#(array[i].Length)');
}
And if alert is intended as server-side:
// note this might need to be #for, depending on the line immediately before
for(var i = 0 ; i < array.Length; i++) {
alert(array[i].Length);
}

Delete row of 2D string array in C#

I am making a program that stores data in a 2D array. I would like to be able to delete rows from this array. I cannot figure out why this code doesn't work:
for (int n = index; n < a.GetUpperBound(1); ++n)
{
for (int i = 0; i < a.GetUpperBound(0); ++i)
{
a[i, n] = a[i, n + 1];
}
}
Could someone please help me out? I would like it to delete a single row and shuffle all the rows below it up one place. Thankyou!
you need to create a new array if you want to delete an item
try something like this
var arrayUpdated = new string[a.GetUpperBound(1)][a.GetUpperBound(0)-1];
for (int n = index; n < a.GetUpperBound(1); n++)
{
for (int i = 0; i < a.GetUpperBound(0); i++)
{
arrayUpdated [i, n] = a[i, 1];
}
}
The nested for loop method here works well: https://stackoverflow.com/a/8000574
Here's a method that converts the outer loop of the [,] array method above to use linq. Using linq here is only recommended if you are also doing other things with linq during the traversal.
public T[,] RemoveRow<T>(T[,] array2d, int rowToRemove)
{
var resultAsList = Enumerable
.Range(0, array2d.GetLength(0)) // select all the rows available
.Where(i => i != rowToRemove) // except for the one we don't want
.Select(i => // select the results as a string[]
{
T[] row = new T[array2d.GetLength(1)];
for (int column = 0; column < array2d.GetLength(1); column++)
{
row[column] = array2d[i, column];
}
return row;
}).ToList();
// convert List<string[]> to string[,].
return CreateRectangularArray(resultAsList); // CreateRectangularArray() can be copied from https://stackoverflow.com/a/9775057
}
used Enumerable.Range to iterate all rows as done in https://stackoverflow.com/a/18673845
Shouldn't ++i be i++? ++i increments before matrix operation is performed(ie pre-increment)

Categories