Skip to main content

Interchange the diagonal of a matrix in typescript

Example to interchange the diagonal of matrix

Ts program for Interchange the diagonal of a matrix. Here mentioned other language solution.

/*
  TypeScript program for
  Swap diagonal elements of matrix using recursion
*/
class Exchange
{
	// Method which are perform swap operation
	// Here x and y indicate start and end rows
	// p and q indicates start and end columns
	public static swapDiagonal(matrix: number[][], 
  		x: number, y: number, p: number, q: number)
	{
		if (x >= y || p >= q)
		{
			return;
		}
		var temp = matrix[x][p];
		// Swap the element value
		matrix[x][p] = matrix[x][q];
		matrix[x][q] = temp;
		temp = matrix[y][p];
		// Swap the element value
		matrix[y][p] = matrix[y][q];
		matrix[y][q] = temp;
		Exchange.swapDiagonal(matrix, x + 1, 
                              y - 1, p + 1, q - 1);
	}
	// Display matrix elements
	public static showMatrix(matrix: number[][])
	{
		console.log(matrix);
	}
	public static main()
	{
		// Define matrix element
		var matrix: number[][] = [
			[1, 2, 3, 4],
			[5, 6, 7, 8],
			[9, 10, 11, 12],
			[13, 14, 15, 16]
		];
		// Assume N X N matrix
		var n = matrix.length;
		// Display element
		Exchange.showMatrix(matrix);
		// interchange request
		Exchange.swapDiagonal(matrix, 0, n - 1, 0, n - 1);
		// Display element
		Exchange.showMatrix(matrix);
	}
}
Exchange.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

Output

[ [ 1, 2, 3, 4 ],
  [ 5, 6, 7, 8 ],
  [ 9, 10, 11, 12 ],
  [ 13, 14, 15, 16 ] ]
[ [ 4, 2, 3, 1 ],
  [ 5, 7, 6, 8 ],
  [ 9, 11, 10, 12 ],
  [ 16, 14, 15, 13 ] ]




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment