fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class TheDotProduct2D {
  6.  
  7. public static void main(String[] args) {
  8. int[][] my2D_1= {{1,3},{4,6},{15,16}};
  9. System.out.println("Original Vector: ");
  10. PrintVect2D(my2D_1);
  11.  
  12. int rows= my2D_1.length;
  13. int cols= my2D_1[0].length;
  14. int[][] my2D_2 = new int[cols][rows];
  15. my2D_2=Transpose2D(my2D_1);
  16.  
  17. System.out.println("\nTransposed Vector: ");
  18. PrintVect2D(my2D_2);
  19. System.out.println("\nDot Product of two Vectors: ");
  20. DotProd2D(my2D_1,my2D_2);
  21. }
  22. public static int[][] Transpose2D(int[][] x_arr) {
  23. int cols=x_arr[0].length;
  24. int rows=x_arr.length;
  25. int trans_arr[][] = new int[cols][rows];
  26. for(int i=0; i<rows; i++) {
  27. for(int j=0; j<cols; j++) {
  28. trans_arr[j][i]=x_arr[i][j];
  29. }
  30. }
  31. return (trans_arr);
  32. }
  33.  
  34. // your code here for new method DotProd()
  35. public static void DotProd2D(int[][] x, int[][] y) {
  36. int row = x.length;
  37. int col = y[0].length;
  38. int temp[][]=new int[row][col];
  39. for(int i=0;i<row;i++){
  40. for(int j=0;j<col;j++){
  41. temp[i][j]=0;
  42. for(int k=0;k<x[1].length;k++){
  43. temp[i][j]+=x[i][k]*y[k][j];
  44. }
  45. }
  46. }
  47. PrintVect2D(temp);
  48. return;
  49. }
  50.  
  51. public static void PrintVect2D(int[][] vect) {
  52. System.out.print("{ ");
  53. for(int i=0; i<vect.length; i++) {
  54. if(i>0)
  55. System.out.print(" ");
  56. for(int j=0; j<vect[0].length; j++) {
  57. if(j<vect[0].length-1)
  58. System.out.print(vect[i][j]+", ");
  59. else
  60. System.out.print(vect[i][j]);
  61. }
  62. if(i<vect.length-1)
  63. System.out.println("");
  64. else
  65. System.out.println(" }");
  66. }
  67. }
  68. }
Success #stdin #stdout 0.12s 48008KB
stdin
Standard input is empty
stdout
Original Vector: 
{ 1, 3
  4, 6
  15, 16 }

Transposed Vector: 
{ 1, 4, 15
  3, 6, 16 }

Dot Product of two Vectors: 
{ 10, 22, 63
  22, 52, 156
  63, 156, 481 }