In: Computer Science
Hi, Please find the solution and rate the answer:
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random;
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Random; class Scratch { public static void main(String[] args) { List<Integer> matrix1 = new LinkedList<>(); List<Integer> matrix2 = new LinkedList<>(); Random x = new Random(); for (int i = 0; i < 9; i++) { matrix1.add(x.nextInt(100)); matrix2.add(x.nextInt(100)); } for (int i = 0; i < 9; i++) { System.out.print(matrix1.get(i)+"\t"); } System.out.println(); System.out.println(); for (int i = 0; i < 9; i++) { System.out.print(matrix1.get(i)+" \t"); if((i+1)%Math.sqrt(9)==0) System.out.println(); } System.out.println(); for (int i = 0; i < 9; i++) { System.out.print(matrix2.get(i) + " \t"); if((i+1)%Math.sqrt(9)==0) System.out.println(); } System.out.println(); System.out.println("_________________________________"); List<Integer> mat = add(matrix1,matrix2); for (int i = 0; i < mat.size(); i++) { System.out.print(mat.get(i)+", "); if((i+1)%Math.sqrt(9)==0) System.out.println(); } System.out.println(); System.out.println(); } static List<Integer> add(List<Integer> mat1,List<Integer> mat2){ int size=mat1.size(); if(mat1.size()!=mat2.size()) return null; List<Integer> mat = new LinkedList<>(); for (int i = 0; i < size; i++) { mat.add(mat1.get(i)+mat2.get(i)); } return mat; } }
Output: Addition of 2 arrays in last line