Sunday, 31 May 2015

Transpose a 2 Dimensional Array in c#

In this post we are going to see how to Transpose a 2 Dimensional array with out restriction in the Type.Now we can see the generic logic to implement this.

Program.cs

           int[,] count = new int[3, 3]
            {
                {1,2,3},
                {4,5,6},
                {8,3,1}
            };

            Console.WriteLine("\n*************************\n");
            count.PrintMatrix();

            Console.WriteLine("\n********  Transpose a Matrix **********\n");
            int [,] Transpose = Algorithm.TransposeMatrix(count);

            Transpose.PrintMatrix();

            string[,] wCount = new string[2, 3] {
              {"Algo","Extn","Where"},
              {"Cv","What","Sample"}
            };

            Console.WriteLine("\n*************************\n");
            wCount.PrintMatrix();

            string[,] Tword = Algorithm.TransposeMatrix(wCount);
            Console.WriteLine("\n********    Transpose a Matrix   *********\n");

            Tword.PrintMatrix();




Logic 

    public class Algorithm
    {          
        public static T[,] TransposeMatrix<T>(T[,] matrix )
        {           
            int dimension = matrix.Rank;
            int rows = matrix.GetLength(0);
            int columns = matrix.GetLength(1);
           
            T[,] Tmatrix= new T[columns,rows];

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    Tmatrix[j, i] = matrix[i, j];
                }
            }

            return Tmatrix;
        }
    }


    public static class Extension
    {
        public static void PrintMatrix<T>(this T[,] matrix)
        {
            int rows = matrix.GetLength(0);
            int columns = matrix.GetLength(1);

            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < columns; j++)
                {
                    Console.Write(matrix[i, j] + "\t");
                }
                Console.WriteLine(Environment.NewLine);
            }

        }
    } 



Output





From this post you can see how to Transpose a two Dimensional Array.

2 comments:

  1. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai velachery | dot net training institute in velachery

    ReplyDelete
  2. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training and placement in chennai | best dot net training in chennai

    ReplyDelete