Question #53291

Write a method multiply() that takes two square matrices of the same
dimensionasarguments andproduces their product(another square matrix ofthat
samedimension). Extra credit: Make your program work wheneverthe number of
rows in the first matrix is equalto the number of columns in the second matrix.
* Write a method any() that takes an arrayof bool ean values as argument
and returns true if any of the entries in the array is true, and fal se otherwise.
Write a method all() that takes an array of bool ean values as argument and re
turns true if allof the entries in the arrayaretrue, and fal se otherwise.
1

Expert's answer

2015-07-09T09:13:02-0400
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkg55291;
public class Main {
public static int[][] multiply(int[][] A, int[][] B) throws IllegalArgumentException{
int rowsA = A.length;
int columnsA = A[0].length;
int rowsB = B.length;
int columnsB = B[0].length;
if (columnsA != rowsB) {
throw new IllegalArgumentException("Wrong dimensions! Cannot multiply.");
}
int[][] result = new int[rowsA][columnsB];
// Multiply row from A by column from B
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < columnsB; j++) {
// Clear the cell
result[i][j] = 0;
// Multiply
for (int k = 0; k < columnsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
public static boolean any(boolean[] anyBoolean){
boolean result = false;
for (int i = 0; i < anyBoolean.length; i++) {
if (anyBoolean[i] == true) {
result = true;
break;
}
}
return result;
}
public static boolean all(boolean[] anyBoolean){
boolean result = true;
for (int i = 0; i < anyBoolean.length; i++) {
if (anyBoolean[i] == false) {
result = false;
break;
}
}
return result;
}
public static void main(String[] args) throws Exception {
int[][] m1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] m2 = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int[][] m3 = multiply(m1, m2);
int[][] expected = {{30, 24, 18}, {84, 69, 54}, {138, 114, 90}};
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
System.out.print(m3[i][j] + "\t");
if(m3[i][j] != expected[i][j]) {
throw new Exception("Wrong result!");
}
}
System.out.println();
}
boolean[] arr1 = {false, false, false};
boolean[] arr2 = {false, false, false, true, false, false, false};
boolean[] arr3 = {true, true, true, true};
System.out.println(any(arr1));
System.out.println(any(arr2));
System.out.println(any(arr3));
System.out.println(all(arr1));
System.out.println(all(arr2));
System.out.println(all(arr3));
}


Assignmentexpert.com

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS