I have to flatted a 3d array in order to be serialized.
Let's start with this:
int[,,] array3D = new int[,,] {
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
which makes it like this (something like 1,2,3,4,...,24):
So now I have this s/r
public static T[] Flatten<T>(T[,,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
int rows2 = arr.GetLength(2);
T[] arrFlattened = new T[rows0 * rows1* rows2];
int i, j, k;
for (k = 0; k < rows2; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows0; i++)
{
var test = arr[i, j, k];
int index = i + j * rows0 + k * rows1;
arrFlattened[index] = test;
}
}
}
return arrFlattened;
}
which flattens the 3d matrix into a 1d array
I am not smart enough to understand if the procedure is correct but let's go further.
I then Expand with the following s/r
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
for (int k = 0; k < rows2; k++)
{
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
T test = arr[i + j * rows0 + k * rows1];
arrExpanded[i, j, k] = test;
}
}
}
return arrExpanded;
}
but the result is the following:
So nothing like 1,2,3,4,5....24
I know that the error might be a trivial one but try as I might I can't find it.
Thank in advance.
Patrick
Thanks for helping all 3 solution were amazing and working but I chose the one more easily to understand and debug for me
I am assuming that you want to know what is the mistake in your code more than you want to know the quickest way to get to the answer. Your index calculation is wrong. You are calculating it like this:
int index = i + j * rows0 + k * rows1;
But you actually need to multiply the last term not just by rows1 but by rows0 too:
int index = i + j * rows0 + k * rows1 * rows0;
Also, it makes sense to swap the order of dimensions that are iterated in for loops to get results in order. The final code for that would be:
public static T[] Flatten<T>(T[,,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
int rows2 = arr.GetLength(2);
T[] arrFlattened = new T[rows0 * rows1* rows2];
int i, j, k;
for (k = 0; k < rows0; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows2; i++)
{
var test = arr[k, j, i];
int index = i + j * rows2 + k * rows1 * rows2;
arrFlattened[index] = test;
}
}
}
return arrFlattened;
}
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
int i, j, k;
for (k = 0; k < rows0; k++)
{
for (j = 0; j < rows1; j++)
{
for (i = 0; i < rows2; i++)
{
T test = arr[i + j * rows2 + k * rows1 * rows2];
arrExpanded[k, j, i] = test;
}
}
}
return arrExpanded;
}
You could give this a go:
void Main()
{
int[,,] array3D = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
var flattened = array3D.Cast<int>().ToArray();
var restored = Expand(flattened, 3, 4);
}
public static T[,,] Expand<T>(T[] arr, int rows0, int rows1)
{
int length = arr.GetLength(0);
int rows2 = length / rows0 / rows1;
int x = 0;
T[,,] arrExpanded = new T[rows0, rows1, rows2];
for (int i = 0; i < rows0; i++)
{
for (int j = 0; j < rows1; j++)
{
for (int k = 0; k < rows2; k++)
{
T test = arr[x++];
arrExpanded[i, j, k] = test;
}
}
}
return arrExpanded;
}
It worked fine for me.
With a help of Linq OfType<T>(), it's easy to have int[] from any multidimensional array:
var result = source.OfType<int>().ToArray();
Demo:
using System.Linq;
...
int[,,] array3D = new int[,,] {
{ { 1, 2}, { 3, 4}, { 5, 6}, { 7, 8 } },
{ { 9, 10}, { 11, 12}, { 13, 14}, {15, 16 } },
{ { 17, 18}, { 19, 20}, { 21, 22}, {23, 24 } },
};
var result = array3D.OfType<int>().ToArray();
Console.Write(string.Join(", ", result));
Outcome:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24
We can use modulo arithmetics to Expand array back:
private static T[,,] Expand<T>(T[] value, int length1, int length2, int length3) {
T[,,] result = new T[length1, length2, length3];
for (int i = 0; i < value.Length; ++i) {
int r = i / (length3 * length2);
int c = i / length3 % length2;
int h = i % length3;
result[r, c, h] = value[i];
}
return result;
}
E.g.
int[,,] back = Expand(result, 3, 4, 2);
To flatten a multidimensional array just use Cast<T>().ToArray().
var d3 = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
var d1 = d3.Cast<int>().ToArray();
Console.WriteLine(string.Join(" ", d1));
Gives:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
To expand use this:
static int[,,] Expand(int[] array, int size2, int size3)
{
var size = new[] { array.Length / size2 / size3, size2, size3 };
var res = Array.CreateInstance(typeof(int), size);
for (var i = 0; i < array.Length; i++)
res.SetValue(array[i], GetMultidimensionalIndex(i, size));
return (int[,,])res;
}
static int[] GetMultidimensionalIndex(int index, int[] size)
{
var factors = size.Select((item, i) => size.Skip(i).Aggregate((a, b) => a * b)).ToArray();
var factorsHelper = factors.Zip(factors.Skip(1).Append(1), (Current, Next) => new { Current, Next }).ToArray();
return factorsHelper.Select(item => index % item.Current / item.Next).ToArray();
}
Usage:
var d3 = new int[,,]
{
{ { 1, 2 }, { 3, 4 }, {5,6 }, {7,8 } },
{ { 9, 10}, { 11, 12},{ 13,14} , {15,16 }},
{ { 17, 18}, { 19, 20},{ 21,22}, {23,24 } }
};
Console.WriteLine("Original:");
Print3DArray(d3);
var flat = d3.Cast<int>().ToArray();
Console.WriteLine("Flat:");
Console.WriteLine(string.Join(" ", flat));
var expanded = Expand(flat, d3.GetLength(1), d3.GetLength(2));
Console.WriteLine("Expanded:");
Print3DArray(expanded);
with helper method:
static void Print3DArray(int[,,] array)
{
Console.WriteLine("{");
for (int i = 0; i < array.GetLength(0); i++)
{
Console.Write(" {");
for (int j = 0; j < array.GetLength(1); j++)
{
Console.Write(" {");
for (int k = 0; k < array.GetLength(2); k++)
{
Console.Write($" {array[i, j, k]}");
}
Console.Write(" }");
}
Console.WriteLine(" }");
}
Console.WriteLine("}");
}
Gives:
Original:
{
{ { 1 2 } { 3 4 } { 5 6 } { 7 8 } }
{ { 9 10 } { 11 12 } { 13 14 } { 15 16 } }
{ { 17 18 } { 19 20 } { 21 22 } { 23 24 } }
}
Flat:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Expanded:
{
{ { 1 2 } { 3 4 } { 5 6 } { 7 8 } }
{ { 9 10 } { 11 12 } { 13 14 } { 15 16 } }
{ { 17 18 } { 19 20 } { 21 22 } { 23 24 } }
}
Related
The following picture is retrieved from Wikipedia:
I haven't understood this part:
I have two questions here:
Where did they obtain [8,4,1,2] from and what did they want to tell us by that?
Take a look at cell [0, 0] whose value is 13. If I go clockwise along with its contouring values, I obtain the binary string 0010 which is 2. How does the 1st cell-value become 13?
.
enum What
{
lines, surface, both
}
class Program
{
public static void Print(int[,] data, int xn, int yn)
{
for (int j = 0; j < yn; j++)
{
for (int i = 0; i < xn; i++)
{
Console.Write(data[i,j] + ", ");
}
Console.WriteLine();
}
}
public static int[,] normalize(int[,] data, int xn, int yn)
{
for (int j = 0; j < yn; j++)
{
for (int i = 0; i < xn; i++)
{
if (data[i, j] > 1)
{
data[i, j] = 0;
}
else
{
data[i, j] = 1;
}
}
}
return data;
}
public static int[,] marching_square(int x, int y, int[,] data, int isovalue, What what)
{
int xn = x;
int yn = y;
data = normalize(data, xn, yn);
int[,] bitMask = new int[xn - 1, yn - 1];
for (int j = 0; j < yn - 1; j++)
{
for (int i = 0; i < xn - 1; i++)
{
StringBuilder sb = new StringBuilder();
sb.Append(data[i, j]);
sb.Append(data[i, j + 1]);
sb.Append(data[i + 1, j]);
sb.Append(data[i + 1, j + 1]);
bitMask[i, j] = Convert.ToInt32(sb.ToString(), 2);
}
}
return bitMask;
}
static void Main(string[] args)
{
int[,] data = new int[,] {
{ 1,1,1,1,1 },
{ 1,2,3,2,1 },
{ 1,3,3,3,1 },
{ 1,2,3,2,1 },
{ 1,1,1,1,1 }
};
Print(data, 5,5);
int[,] bitMask = marching_square(5,5,data, 0, What.lines);
Print(bitMask, 4, 4);
}
}
Output:
1, 1, 1, 1, 1,
1, 2, 3, 2, 1,
1, 3, 3, 3, 1,
1, 2, 3, 2, 1,
1, 1, 1, 1, 1,
14, 10, 10, 11,
12, 0, 0, 3,
12, 0, 0, 3,
13, 5, 5, 7,
I inverted the bits. But, the output looks different.
Let's say I have an array like this :
9 1 2 0
1 5 2 5
7 1 6 3
4 3 2 7
I want to be able to create a loop that goes through the array vertically and horizontally to see if there's any duplicates.
For example, it will first check 9 1 7 4 to see if there's a dups. Then 1 5 1 3 and so on.
After that, it'll do 9 1 2 0 (which will tell me there's a dup), then 1 5 2 5 7, etc etc.
How can I do that?
While possible, a nested loops solution may not be the more straightforward way of solving it. In this case, using LINQ is must easier :
var matrix = new int[4, 4]
{
{ 9, 1, 2, 0 },
{ 1, 5, 2, 5 },
{ 7, 1, 6, 3 },
{ 4, 3, 2, 7 }
};
for (int i = 0; i < 4; i++)
{
var row = Enumerable.Range(0, 4).Select(x => matrix[i, x]);
if (row.Distinct().Count() != 4)
Console.WriteLine("Duplicated value in row {0} : {1}",
i + 1, string.Join(", ", row));
}
for (int i = 0; i < 4; i++)
{
var column = Enumerable.Range(0, 4).Select(x => matrix[x, i]);
if (column.Distinct().Count() != 4)
Console.WriteLine("Duplicated value in column {0} : {1}",
i + 1, string.Join(", ", column));
}
Output :
Duplicated value in row 2 : 1, 5, 2, 5
Duplicated value in column 2 : 1, 5, 1, 3
Duplicated value in column 3 : 2, 2, 6, 2
I have gotten a working solution using nested For Loops. This will write "Nothing" to the console when the index used to check(horizontal or vertical) is zero to avoid an ArrayIndexOutOfBoundsException. It writes "Duplicate No." and then the number that was duplicate to the console. I have posted my full working example below along with the output from console:
For horizontal:
int[,] array = new int[5, 4] { { 1, 2, 3, 4 }, { 5, 5, 5, 5 }, { 9, 5, 11, 12 }, { 13, 14, 15, 16 }, { 17, 18, 19, 20 } } ;
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
if (j == 0)
{
Console.WriteLine("Nothing");
}
else if (array[i, j] == array[i, j - 1])
{
Console.WriteLine("Duplicate No." + array[i, j].ToString());
}
}
}
For vertical:
for (int i = 0; i < array.GetLength(1); i++)
{
for (int j = 0; j < array.GetLength(0); j++)
{
if (j == 0)
{
Console.WriteLine("Nothing");
}
else if (array[j, i] == array[j - 1, i])
{
Console.WriteLine("Duplicate No." + array[i, j].ToString());
}
}
}
Output from both horizontal and vertical:
Nothing
Nothing
Duplicate No. 5
Duplicate No. 5
Duplicate No. 5
Nothing
Nothing
Nothing
Nothing
Nothing
Duplicate No. 5
Nothing
Nothing
I create a class that allow you to enumerate through the array
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication88
{
class Program
{
static void Main(string[] args)
{
EnumerateArray eArray = new EnumerateArray() {
new List<int>() {1,2,3,4},
new List<int>() {5,6,7,8},
new List<int>() {9,10,11,12},
new List<int>() {13,14,15,16},
new List<int>() {17,18,19,20}
};
foreach (List<int> x in eArray)
{
Console.WriteLine(string.Join(",", x.Select(y => y.ToString()).ToArray()));
}
Console.ReadLine();
}
}
public class EnumerateArray : IEnumerator, IEnumerable
{
public List<List<int>> myArray { get; set;}
int row = 0;
int col = 0;
int numCols = 0;
int numRows = 0;
public int Count { get; set; }
public int[] current = null;
Boolean finishedCol = false;
public EnumerateArray()
{
myArray = new List<List<int>>();
}
public EnumerateArray(List<List<int>> array)
{
myArray = array;
Reset();
numRows = array.Count;
numCols = array[0].Count;
Count = numCols + numRows;
}
public void Add(List<int> array)
{
myArray.Add(array);
numRows = myArray.Count;
numCols = array.Count;
Count = numCols + numRows;
}
public void Add(List<List<int>> array)
{
myArray = array;
Reset();
numRows = array.Count;
numCols = array[0].Count;
Count = numCols + numRows;
}
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
public EnumerateArray GetEnumerator()
{
return new EnumerateArray(myArray);
}
public bool MoveNext()
{
Boolean done = true;
if (finishedCol == false)
{
if (col < numCols - 1)
{
col++;
}
else
{
finishedCol = true;
row = 0;
}
}
else
{
if (row < numRows - 1)
{
row++;
}
else
{
done = false;
}
}
return done;
}
public void Reset()
{
row = -1;
col = -1;
finishedCol = false;
Count = numCols + numRows;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public List<int> Current
{
get
{
try
{
List<int> _array = new List<int>();
if (finishedCol == false)
{
for (int _row = 0; _row < numRows; _row++)
{
_array.Add(myArray[_row][ col]);
}
}
else
{
_array.AddRange(myArray[row]);
}
return _array;
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
}
I have made 8x8 matrix using c#, and now I need to transpose the matrix. Can you help me to transpose the matrix?
This is my matrix
public double[,] MatriksT(int blok)
{
double[,] matrixT = new double[blok, blok];
for (int j = 0; j < blok ; j++)
{
matrixT[0, j] = Math.Sqrt(1 / (double)blok);
}
for (int i = 1; i < blok; i++)
{
for (int j = 0; j < blok; j++)
{
matrixT[i, j] = Math.Sqrt(2 / (double)blok) * Math.Cos(((2 * j + 1) * i * Math.PI) / 2 * blok);
}
}
return matrixT;
}
public double[,] Transpose(double[,] matrix)
{
int w = matrix.GetLength(0);
int h = matrix.GetLength(1);
double[,] result = new double[h, w];
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
result[j, i] = matrix[i, j];
}
}
return result;
}
public class Matrix<T>
{
public static T[,] TransposeMatrix(T[,] matrix)
{
var rows = matrix.GetLength(0);
var columns = matrix.GetLength(1);
var result = new T[columns, rows];
for (var c = 0; c < columns; c++)
{
for (var r = 0; r < rows; r++)
{
result[c, r] = matrix[r, c];
}
}
return result;
}
}
And that is how to call it:
int[,] matris = new int[5, 8]
{
{1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 },
{9 , 10, 11, 12, 13, 14, 15, 16},
{17 , 18, 19, 20, 21, 22, 23, 24},
{25 , 26, 27, 28, 29, 30, 31, 32},
{33 , 34, 35, 36, 37, 38, 39, 40},
};
var tMatrix = Matrix<int>.TransposeMatrix(matris);
Your matrix is not a "perfect square" one. You need a result (transposedMatris) matrix. If your matrix were a perfect square one it would be enough to swap(a[i, j], a[j, i]) on the same matrix.
Generic type class has static method and the method should be called as below.
int[,] transposedMatris = Matrix.TransposeMatrix<int>(matris);
dumpMatrix(transposedMatris);
Dump the transposed matrix on console.
// Using Generics (dump string, integer, decimal, string)
public static void dumpMatrix<T>(T[,] a)
{
int m = a.GetLength(0);
int n = a.GetLength(1);
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
Console.Write(a[i, j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
Transposed matrix dump:
1 9 17 25 33
2 10 18 26 34
3 11 19 27 35
4 12 20 28 36
5 13 21 29 37
6 14 22 30 38
7 15 23 31 39
8 16 24 32 40
I am not süre but you need to rotate an image clockwise 90 degrees follow below steps.
Step 1: Transpose Matrix
Step 2: Flip horizontally
int[,] a = new int[5, 5] {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}
};
int m = a.GetLength(0);
int n = a.GetLength(1);
//dumpMatrix(a);
// Step 1: Transpose Matrix
int temp = 0;
for (int i = 0; i < m; i++)
{
for (int j = i; j < n; j++)
{
temp = a[i, j];
a[i, j] = a[j, i];
a[j, i] = temp;
}
}
//Console.WriteLine("Step 1: Transpose Matrix");
//dumpMatrix(a);
// Step 2: Flip horizontally
for (int i = 0; i < m; i++)
{
for (int j = 0; j < (n/2); j++)
{
temp = a[i, j];
a[i, j] = a[i, n - 1 - j];
a[i, n - 1 - j] = temp;
}
}
//Console.WriteLine("Step 2: Flip horizontally");
//dumpMatrix(a);
Why does output shows only 13 card but only suit, club. And not the rest of it ? Help anyone ? Is there something wrong with my loop.
public class deck {
public Card[] deck; // field
public deck() {
deck = new Card[52]; // store into deck
}
public void DeckCreation() {
String[] suit = { "Spades", "Hearts", "Diamonds", "Clubs" };//Array for suit
int[] number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; // Array for number
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[i]);// Card instantiate
if (deck[i] == null) {
deck[i] = c;
}
}
}
}
public void displayDeck() {
for (int i = 0; i <deck.length; i++) {
if (deck[i] != null) {
deck[i].display(); // display
}
}
}
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[i]); // Card instantiate
if (deck[i] == null)
{
deck[i] = c; // Repeatedly trying to access index 0 to suit.length-1
}
}
}
It should be
for (int i = 0; i <suit.length ; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[n]); // Card instantiate
// Using (i*number.length + n) will get you from index 0 to 51
if (deck[(i*number.length + n)] == null)
{
deck[(i*number.length + n)] = c; // Accessing index 0 to 51
}
}
}
(0 * 13 + 0) = 0, (0 * 13 + 1) = 1, (0 * 13 + 2) = 2..
(3 * 13 + 0) = 39, (3 * 13 + 1) = 40, ..., (3 * 13) + 12 = 51..
Card c = new Card(suit[i], number[i]);// Card instantiate
This should be
Card c = new Card(suit[i], number[n]);// Card instantiate
I dont't have any code for this, but I do want to know how I could do this. I use visual studio 2010 C# if that matters.
Thanks
Jason
public static void Print2DArray<T>(T[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i,j] + "\t");
}
Console.WriteLine();
}
}
you can print it all on one line
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
Console.WriteLine(String.Join(" ", array2D.Cast<int>()));
output
1 2 3 4 5 6 7 8
You should read MSDN:Using foreach with Arrays
int[,] numbers2D = new int[3, 2] { { 9, 99 }, { 3, 33 }, { 5, 55 } };
// Or use the short form:
// int[,] numbers2D = { { 9, 99 }, { 3, 33 }, { 5, 55 } };
foreach (int i in numbers2D)
{
System.Console.Write("{0} ", i);
}
// Output: 9 99 3 33 5 55
//The following are three ways to print any 2d arrays to console:
int[,] twoDArray = new int[3, 4]{ {2,5,55,44},{10,45,5,22 },{ 67,34,56,77} };
Console.WriteLine("Array Code Out Method:1");
int rows = twoDArray.GetLength(0); // 0 is first dimension, 1 is 2nd
//dimension of 2d array
int cols = twoDArray.GetLength(1);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
Console.Write("\t" + twoDArray[i, j]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method: 2");
for (int x = 0; x <= twoDArray.GetUpperBound(0); x++)
{
for (int y = 0; y <= twoDArray.GetUpperBound(1); y++)
{
Console.Write("\t"+ twoDArray[x,y]);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
}
Console.WriteLine("Array Code Out Method:3");
foreach (int items in twoDArray)
{
Console.Write(""+ "\t" +items);
//output: 2 5 55 44 10 45 5 22 67 34 56 77
}
//string example
string[,] friendNames = new string[,] { {"Rosy","Amy"},
{"Peter","Albert"}
};
foreach (string str in friendNames)
{
Console.WriteLine(str);
}
The following is an example...
static void Main()
{
// A. 2D array of strings.
string[,] a = new string[,]
{
{"ant", "aunt"},
{"Sam", "Samantha"},
{"clozapine", "quetiapine"},
{"flomax", "volmax"},
{"toradol", "tramadol"}
};
// B. Get the upper bound to loop.
for (int i = 0; i <= a.GetUpperBound(0); i++)
{
string s1 = a[i, 0]; // ant, Sam, clozapine...
string s2 = a[i, 1]; // aunt, Samantha, quetiapine...
Console.WriteLine("{0}, {1}", s1, s2);
}
Console.WriteLine();
}
int[,] matrix = new int[2, 2] { {2, 2}, {1, 1} };
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int k = 0; k < matrix.GetLength(1); k++ )
{
//put a single value
Console.Write(matrix[i,k]);
}
//next row
Console.WriteLine();
}
private int[,] MirrorH(int[,] matrix)
{
int[,] MirrorHorizintal = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j ++)
{
MirrorHorizintal[i, j] = matrix[i, 3 - j];
}
}
return MirrorHorizintal;
}
Try like this..
int[,] matrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(1);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
Console.Read();
Below is multiple solution to how to implement multidimentional array, I think it is pretty straight forward in c#.
using System;
using System.Collections.Generic;
namespace DataStructure
{
class Program : SortedZeros
{
static void Main(string[] args)
{
// Two-Dimensional Array
int[,] numbers2D = new int[3, 2]
{
{ 9, 99 },
{ 3, 33 },
{ 5, 55 }
};
// 3 * 3
int[,] dataTest2D = new int[3, 3]
{
{3, 5, 7},
{4, 3, 8},
{9, 6, 9},
};
// A similar array with string elements.
int[,] matrix = new int[4, 4]
{
{1, 2, 3, 6},
{4, 5, 6, 4},
{7, 8, 9, 6},
{7, 8, 9, 2},
};
int rowLength = matrix.GetLength(0);
int colLength = matrix.GetLength(0);
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
Console.Write(string.Format("{0} ", matrix[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
// using foreach to print out the 2 * 2 in one straightline
foreach (int i in numbers2D)
{
Console.Write("{0} ", i);
}
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i < dataTest2D.GetLength(0); i++)
{
for (int j = 0; j < dataTest2D.GetLength(1); j++)
{
Console.Write(string.Format("{0} ", dataTest2D[i, j]));
}
Console.Write(Environment.NewLine + Environment.NewLine);
}
}
}
}
Explanation:
1. create an array
2. Create 2 for loops (one inside the other)
3. In "j" loop, pass matrix (roomString in our case) as parameter.
4. Add a "+" symbol (concatenate) it with a " " (empty space)
5. In "i" loop, have a "cw tab tab" --> Console.WriteLine();
Code:
string[,] roomString = new string[4, 4]
{
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" },
{"0","0","0","0" }
};
for (int i = 0; i < roomString.GetLength(0); i++)
{
for (int j = 0; j < roomString.GetLength(1); j++)
{
Console.Write(roomString[i,j]+" ");
}
Console.WriteLine();
}
Helper function to get any row:
public static int[] GetRow(int[,] mat, int rowNumber)
=> Enumerable.Range(0, mat.GetLength(1))
.Select(i => mat[rowNumber, i])
.ToArray();
Print row values in new line:
int[,] mat = new int[2,2];
for (int i =0; i < mat.GetLength(0); i++)
{
Console.WriteLine(string.Join(",", GetRow(mat, i)));
}
Do it like this:
static public void Print2DArray(int[][] A)
{
foreach (int[] row in A)
{
foreach (int element in row)
{
Console.Write(element.ToString() + " ");
}
Console.WriteLine();
}
}