diff --git a/java/matrix/MatrixAddition.java b/java/matrix/MatrixAddition.java new file mode 100644 index 000000000..ddc0a2d5c --- /dev/null +++ b/java/matrix/MatrixAddition.java @@ -0,0 +1,18 @@ +public class MatrixAdditionExample{ +public static void main(String args[]){ +//creating two matrices +int a[][]={{1,3,4},{2,4,3},{3,4,5}}; +int b[][]={{1,3,4},{2,4,3},{1,2,4}}; + +//creating another matrix to store the sum of two matrices +int c[][]=new int[3][3]; //3 rows and 3 columns + +//adding and printing addition of 2 matrices +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +c[i][j]=a[i][j]+b[i][j]; //use - for subtraction +System.out.print(c[i][j]+" "); +} +System.out.println();//new line +} +}} \ No newline at end of file diff --git a/java/matrix/matrixSub.java b/java/matrix/matrixSub.java new file mode 100644 index 000000000..828a60a89 --- /dev/null +++ b/java/matrix/matrixSub.java @@ -0,0 +1,18 @@ +public class MatrixSubExample{ +public static void main(String args[]){ +//creating two matrices +int a[][]={{1,3,4},{2,4,3},{3,4,5}}; +int b[][]={{1,3,4},{2,4,3},{1,2,4}}; + +//creating another matrix to store the difference of two matrices +int c[][]=new int[3][3]; //3 rows and 3 columns + +//Subtracting and printing addition of 2 matrices +for(int i=0;i<3;i++){ +for(int j=0;j<3;j++){ +c[i][j]=a[i][j]-b[i][j]; //use - for subtraction +System.out.print(c[i][j]+" "); +} +System.out.println();//new line +} +}} \ No newline at end of file diff --git a/java/sorting/matrixSort.java b/java/sorting/matrixSort.java new file mode 100644 index 000000000..a5de5deb8 --- /dev/null +++ b/java/sorting/matrixSort.java @@ -0,0 +1,36 @@ +import java.util.*; + +public class Main { + public static void main(String[] args) + { + // Initialize the 2D vector with some values + List > v + = new ArrayList<>(Arrays.asList( + new ArrayList<>(Arrays.asList(5, 4, 7)), + new ArrayList<>(Arrays.asList(1, 3, 8)), + new ArrayList<>(Arrays.asList(2, 9, 6)))); + + int n = v.size(); + List x = new ArrayList<>(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + x.add(v.get(i).get(j)); + } + } + Collections.sort(x); + int k = 0; + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + v.get(i).set(j, x.get(k++)); + } + } + + System.out.println("Sorted Matrix Will be:"); + for (List row : v) { + for (int num : row) { + System.out.print(num + " "); + } + System.out.println(); + } + } +}