I have a piece of program that i have to fill. It is supposed to count adjacent numbers in a 5 by 5 binary matrix. For example a matrix like this:
0 1 1 1 0
1 0 0 0 1
1 0 0 0 0
1 0 0 1 0
0 1 0 1 0
Should return 8, you can only move horizontally or vertically.
Here is the code that generates these said matrices and it can't have any modifications after i'm done.
import java.util.Random;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(alkioTaulukko));
System.out.println("");
}
}
}
And finally here is my solution to the problem.
static int laskeSuurinAlue(int[][] matriisi) {
int vierekkaiset = 0;
int rivi = matriisi.length;
int palkki = matriisi[0].length;
for (int r = 0; r < rivi; r++)
{
for (int p = 0; p < palkki; p++)
{
if ((p+1 < palkki) && (matriisi[r][p] == matriisi[r][p+1]))//loops through the rows
vierekkaiset++;
if ((r+1 < rivi) && (matriisi[r][p] == matriisi[r+1][p]))//loops through the columns
vierekkaiset++;
}
}
return vierekkaiset;
}
What happens is that my solution always brings up too big results and i'm failing to see any pattern between each run. However if i use a smaller matrix like this:
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
The result is correctly 4.
And if i use a bigger one like this:
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
The result is always 20.
Finally here is my code at its current state:
import java.util.Random;
import static java.util.Arrays.deepToString;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
int[][] array = {{1, 0, 1}, {0, 1, 1}, {0, 1, 0}};
int[][] arr = {{1,0,1,1,0},
{0,0,1,0,0},
{0,0,1,0,1},
{1,1,1,0,1},
{0,0,1,0,0}
};
for (int kerrat = 0; kerrat < 10; kerrat++) {
int[][] alkioTaulukko = new int[5][5];
System.out.println("Matriisin");
for (int i = 0; i < alkioTaulukko.length; i++) {
System.out.print("");
for (int j = 0; j < alkioTaulukko[i].length; j++) {
alkioTaulukko[i][j] = r.nextInt(2);
System.out.print("" + alkioTaulukko[i][j] + " ");
}
System.out.println("");
}
System.out.print("suurimman yhtenäisen alueen koko on ");
System.out.println(laskeSuurinAlue(arr));//Change to arr,array or alkioTaulukko to run the code with different matrices
System.out.println(deepToString(arr));
System.out.println("");
}
}
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if ((c+1 < colLimit) && (array[r][c] == array[r][c+1]))
counter++;
if ((r+1 < rowLimit) && (array[r][c] == array[r+1][c]))
counter++;
}
}
return counter;
}
}
You're couting the same entry more than once.
Use this code
static int laskeSuurinAlue(int[][] array) {
int counter = 0;
int rowLimit = array.length;
int colLimit = array[0].length;
for (int r = 0; r < rowLimit; r++)
{
for (int c = 0; c < colLimit; c++)
{
if (array[r][c] == 0) {
continue;
}
int sum = array[r][c];
sum += (r + 1 < rowLimit) ? array[r+1][c] : 0;
sum += (c + 1 < colLimit) ? array[r][c+1] : 0;
sum += (r - 1 >= 0 ) ? array[r-1][c] : 0;
sum += (c - 1 >= 0) ? array[r][c-1] : 0;
if (sum > 1) {
counter++;
}
}
}
return counter;
}
Related
Can anyone please point out the mistake, the error its showing is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at com.company.Grid.pushZero(Grid.java:42)
at com.company.Main.main(Main.java:14)
My Code is
package com.company;
import java.util.Random;
public class Grid {
Random rand = new Random();
int newnumber() {
double rand1 = rand.nextDouble();
if (rand1 < 0.2) {
return 4;
} else {
return 2;
}
}
int[][] array = {{0, 0, 0, newnumber()}, {0, 0, 0, 2}, {0, 0, 0, 0}, {0, 0, 0, 0}};
void display() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < array[i].length; ++j) {
System.out.print(array[i][j] + "\t");
}
System.out.print("\n");
}
System.out.print("\n");
}
void pushZero(int[][] array, int n) {
int count1 = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++) {
if (array[i][j] != 1) {
array[count1++][j] = array[i][j];
while (count1 < n) {
array[count1++][j] = 1;
}
} else {
while (count1 < n)
array[count1++][j] = 1;
}
int lastNonOne = 0;
for (int a = n - 1; i >= 0; i--) {
if (array[a][j] == 1)
continue;
if (lastNonOne == 0) {
lastNonOne = a;
}
if (array[i][j] !=0)
array[lastNonOne--][j] = array[i][j];
}
while (lastNonOne >= 0)
array[lastNonOne--][j] = 0;
}
}
}
}
You forgot to reset count1. Or, rather, you've mis-scoped it. It shuold probably be declared 2 nest-levels deeper, right above if (array[i][j]...) - the first loop, count1 is upped to 4 (or rather, upped to whatever n is, but I assume that pushZero is called with n=4), and then next loop, it just carries on where it left off, trying array[4], in effect, and that causes an AIOOBEx exactly as you get it - there is no array[4], there's only array[0] through array[3].
so I'm trying to make a program that rotates a cube shaped grid 90 degree to the right.
The problem I encountered is that temp values (temp1, temp2, temp3, temp4) that I declared in the method keep changes during the process of method.
Assume there is a cube grid,
1 2 3
4 5 6
7 8 9
as I declared
int[] temp1 = grid[0]; in the method
temp1 should be fixed as {1, 2, 3}.
However, when this part of code executes,
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
temp1's value changes as {7, 4, 1} which I didn't not expect
It is really confusing because temp value usually don't change.
Can anyone give me advice to fix this issue?
import java.util.Scanner;
public class a
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int numLine = Integer.parseInt(input.nextLine());
int[][] grid = new int[numLine][numLine];
String[] lines = null;
for (int i = 0; i < numLine; i++)
{
lines = input.nextLine().split(" ");
for (int j = 0; j < numLine; j++)
{
grid[i][j] = Integer.parseInt(lines[j]);
}
}
rotate(grid);
for (int[] i : grid)
{
for (int j : i)
{
System.out.print(j + " ");
}
System.out.println("");
}
input.close();
}
public static void rotate(int[][] grid)
{
//row 0
int[] temp1 = grid[0];
//column 0
int[] temp2 = new int[grid[0].length];
int c = 0;
for (int i = grid[0].length-1; i >= 0; i--)
{
temp2[c] = grid[i][0];
c++;
}
c = 0;
//row last
int[] temp3 = grid[grid[0].length-1];
//column last
int[] temp4 = new int[grid[0].length];
for (int i = grid[0].length-1; i >= 0; i--)
{
temp4[c] = grid[i][grid[0].length-1];
c++;
}
c = 0;
//rotate 90 degree to right
//row 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[0][i] = temp2[i];
}
//column last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][grid[0].length-1] = temp1[i];
}
//row last ==
for (int i = 0; i < grid[0].length; i++)
{
grid[grid[0].length-1][i] = temp4[i];
}
//column 0 ==
for (int i = 0; i < grid[0].length; i++)
{
grid[i][0] = temp3[i];
}
}
}
I was asked to write, to remove the element (lets say k=30) from the array and shift the other elements to its left without using inbuilt methods.
I have tried the below approach.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
I need output like this: [1 2 4 5 6 0 0]
But the output from the above logic is: [1 2 4 5 6 6 6]
Also, I'm worried about using nested for loops here. Is there any way that we can reduce the time complexity with out using any inbuilt methods?
Here is another variant:
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != k) {
arr[j++] = arr[i];
}
}
while (j < arr.length) {
arr[j++] = 0;
}
In order to not change your approach drastically, I would suggest adding another iteration of the array at the end, to insert 0s to count-many indices from the end of your array.
This would be as simple as adding the following snippet:
// nested for loop
// ...
// set trailing elements to 0s
for (int i = 0; i < count ; i++)
arr[arr.length-1-i] = 0;
System.out.println("\n---Modified Array------");
// ...
There are some cleaner/more-efficient ways of solving this problem.
Based exactly on your approach, I went ahead and made a modification to your nested loop to not require another iteration.
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++)
arr[l] = arr[l + 1];
// since we have performed the shifting, we can safely set the last element to 0
arr[arr.length-1] = 0; // <----- this was missing!!
}
}
}
The following code gives the desired result:
int [] arr = { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int elementCount = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
++elementCount;
}
}
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k) {
count++;
for (int j = i; j < arr.length-1; j++) {
arr[j] = arr[j+1];
}
arr[arr.length-1] = 0;
}
if (count == elementCount) {
break;
}
}
I don't know if it helps. This is a simplified aproach, that is easier to read and understand(at least for people that learned C), that does removal as required....
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int i=0;
int j=0;
for(;j<arr.length;i++,j++){
if((arr[i]=arr[j])==k) i--;
}
while(i<j)arr[i++]=0;
System.err.println(Arrays.toString(arr));
}
output:[1, 2, 4, 5, 6, 0, 0]
First version with a small fix on your code. You issue is that the shifted elements need to be replaced by zero. Which require basically an if statement with the arr.length - count
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for (int i = 0; i < arr.length; i++) {
if (arr[i] == k)
count++;
}
for (int j = 0; j < count; j++) {
for (int i = 0; i < arr.length; i++) {
if(i >= arr.length - count){
arr[i] = 0;
}else {
if (arr[i] == k) {
for (int l = i; l < arr.length - 1; l++) {
arr[l] = arr[l + 1];
}
}
}
}
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
Which gives output
---Original Array------
1 2 30 4 5 30 6
---Modified Array------
1 2 4 5 6 0 0
Now, we can simplify the code also
public static void main(String[] args) {
int[] arr = new int[] { 1, 2, 30, 4, 5, 30, 6 };
int k = 30;
int count = 0;
System.out.println("---Original Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
for(int i = 0; i < arr.length; i++){
if(arr[i]==k){
count++;
}else{
arr[i-count] = arr[i];
}
}
for(int i = 1; i <= count; i++){
arr[arr.length - i] = 0;
}
System.out.println("---Modified Array------");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
which give the same output
Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}
I'm trying to make a simple matrix multiplication method using multidimensional arrays ([2][2]). I'm kinda new at this, and I just can't find what it is I'm doing wrong. I'd really appreciate any help in telling me what it is. I'd rather not use libraries or anything like that, I'm mostly doing this to learn how it works. Thank you so much in advance.
I'm declaring my arays in the main method as follows:
Double[][] A={{4.00,3.00},{2.00,1.00}};
Double[][] B={{-0.500,1.500},{1.000,-2.0000}};
A*B should return the identity matrix. It doesn't.
public static Double[][] multiplicar(Double[][] A, Double[][] B){
//the method runs and returns a matrix of the correct dimensions
//(I actually changed the .length function to a specific value to eliminate
//it as a possible issue), but not the correct values
Double[][] C= new Double[2][2];
int i,j;
////I fill the matrix with zeroes, if I don't do this it gives me an error
for(i=0;i<2;i++) {
for(j=0;j<2;j++){
C[i][j]=0.00000;
}
}
///this is where I'm supposed to perform the adding of every element in
//a row of A multiplied by the corresponding element in the
//corresponding column of B, for all columns in B and all rows in A
for(i=0;i<2;i++){
for(j=0;j<2;j++)
C[i][j]+=(A[i][j]*B[j][i]);
}
return C;
}
You can try this code:
public class MyMatrix {
Double[][] A = { { 4.00, 3.00 }, { 2.00, 1.00 } };
Double[][] B = { { -0.500, 1.500 }, { 1.000, -2.0000 } };
public static Double[][] multiplicar(Double[][] A, Double[][] B) {
int aRows = A.length;
int aColumns = A[0].length;
int bRows = B.length;
int bColumns = B[0].length;
if (aColumns != bRows) {
throw new IllegalArgumentException("A:Rows: " + aColumns + " did not match B:Columns " + bRows + ".");
}
Double[][] C = new Double[aRows][bColumns];
for (int i = 0; i < aRows; i++) {
for (int j = 0; j < bColumns; j++) {
C[i][j] = 0.00000;
}
}
for (int i = 0; i < aRows; i++) { // aRow
for (int j = 0; j < bColumns; j++) { // bColumn
for (int k = 0; k < aColumns; k++) { // aColumn
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
public static void main(String[] args) {
MyMatrix matrix = new MyMatrix();
Double[][] result = multiplicar(matrix.A, matrix.B);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
System.out.print(result[i][j] + " ");
System.out.println();
}
}
}
Java. Matrix multiplication.
Tested with matrices of different size.
public class Matrix {
/**
* Matrix multiplication method.
* #param m1 Multiplicand
* #param m2 Multiplier
* #return Product
*/
public static double[][] multiplyByMatrix(double[][] m1, double[][] m2) {
int m1ColLength = m1[0].length; // m1 columns length
int m2RowLength = m2.length; // m2 rows length
if(m1ColLength != m2RowLength) return null; // matrix multiplication is not possible
int mRRowLength = m1.length; // m result rows length
int mRColLength = m2[0].length; // m result columns length
double[][] mResult = new double[mRRowLength][mRColLength];
for(int i = 0; i < mRRowLength; i++) { // rows from m1
for(int j = 0; j < mRColLength; j++) { // columns from m2
for(int k = 0; k < m1ColLength; k++) { // columns from m1
mResult[i][j] += m1[i][k] * m2[k][j];
}
}
}
return mResult;
}
public static String toString(double[][] m) {
String result = "";
for(int i = 0; i < m.length; i++) {
for(int j = 0; j < m[i].length; j++) {
result += String.format("%11.2f", m[i][j]);
}
result += "\n";
}
return result;
}
public static void main(String[] args) {
// #1
double[][] multiplicand = new double[][] {
{3, -1, 2},
{2, 0, 1},
{1, 2, 1}
};
double[][] multiplier = new double[][] {
{2, -1, 1},
{0, -2, 3},
{3, 0, 1}
};
System.out.println("#1\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
// #2
multiplicand = new double[][] {
{1, 2, 0},
{-1, 3, 1},
{2, -2, 1}
};
multiplier = new double[][] {
{2},
{-1},
{1}
};
System.out.println("#2\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
// #3
multiplicand = new double[][] {
{1, 2, -1},
{0, 1, 0}
};
multiplier = new double[][] {
{1, 1, 0, 0},
{0, 2, 1, 1},
{1, 1, 2, 2}
};
System.out.println("#3\n" + toString(multiplyByMatrix(multiplicand, multiplier)));
}
}
Output:
#1
12.00 -1.00 2.00
7.00 -2.00 3.00
5.00 -5.00 8.00
#2
0.00
-4.00
7.00
#3
0.00 4.00 0.00 0.00
0.00 2.00 1.00 1.00
static int b[][]={{21,21},{22,22}};
static int a[][] ={{1,1},{2,2}};
public static void mul(){
int c[][] = new int[2][2];
for(int i=0;i<b.length;i++){
for(int j=0;j<b.length;j++){
c[i][j] =0;
}
}
for(int i=0;i<a.length;i++){
for(int j=0;j<b.length;j++){
for(int k=0;k<b.length;k++){
c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
}
}
}
for(int i=0;i<c.length;i++){
for(int j=0;j<c.length;j++){
System.out.print(c[i][j]);
}
System.out.println("\n");
}
}
Try this,
public static Double[][] multiplicar(Double A[][],Double B[][]){
Double[][] C= new Double[2][2];
int i,j,k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
C[i][j] = 0.00000;
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for (k=0;k<2;k++){
C[i][j]+=(A[i][k]*B[k][j]);
}
}
}
return C;
}
try this,it may help you
import java.util.Scanner;
public class MulTwoArray {
public static void main(String[] args) {
int i, j, k;
int[][] a = new int[3][3];
int[][] b = new int[3][3];
int[][] c = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of array a");
int rowa = sc.nextInt();
int cola = sc.nextInt();
System.out.println("Enter size of array b");
int rowb = sc.nextInt();
int colb = sc.nextInt();
//read and b
System.out.println("Enter elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
a[i][j] = sc.nextInt();
}
System.out.println();
}
System.out.println("Enter elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
b[i][j] = sc.nextInt();
}
System.out.println("\n");
}
//print a and b
System.out.println("the elements of array a");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < cola; ++j) {
System.out.print(a[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("the elements of array b");
for (i = 0; i < rowb; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(b[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
//multiply a and b
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
c[i][j] = 0;
for (k = 0; k < cola; ++k) {
c[i][j] += a[i][k] * b[k][j];
}
}
}
//print multi result
System.out.println("result of multiplication of array a and b is ");
for (i = 0; i < rowa; ++i) {
for (j = 0; j < colb; ++j) {
System.out.print(c[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
}
}
The method mults is a procedure(Pascal) or subroutine(Fortran)
The method multMatrix is a function(Pascal,Fortran)
import java.util.*;
public class MatmultE
{
private static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
double[][] A={{4.00,3.00},{2.00,1.00}};
double[][] B={{-0.500,1.500},{1.000,-2.0000}};
double[][] C=multMatrix(A,B);
printMatrix(A);
printMatrix(B);
printMatrix(C);
double a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
double b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
double[][] c=multMatrix(a,b);
printMatrix(a);
printMatrix(b);
printMatrix(c);
double[][] a1 = readMatrix();
double[][] b1 = readMatrix();
double[][] c1 = new double[a1.length][b1[0].length];
mults(a1,b1,c1,a1.length,a1[0].length,b1.length,b1[0].length);
printMatrix(c1);
printMatrixE(c1);
}
public static double[][] readMatrix() {
int rows = sc.nextInt();
int cols = sc.nextInt();
double[][] result = new double[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = sc.nextDouble();
}
}
return result;
}
public static void printMatrix(double[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%8.3f " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static void printMatrixE(double[][] mat) {
System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
int rows = mat.length;
int columns = mat[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.printf("%9.2e " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static double[][] multMatrix(double a[][], double b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new double[0][0];
if(a[0].length != b.length) return null; //invalid dims
int n = a[0].length;
int m = a.length;
int p = b[0].length;
double ans[][] = new double[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
ans[i][j]=0;
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
}
public static void mults(double a[][], double b[][], double c[][], int r1,
int c1, int r2, int c2){
for(int i = 0;i < r1;i++){
for(int j = 0;j < c2;j++){
c[i][j]=0;
for(int k = 0;k < c1;k++){
c[i][j] += a[i][k] * b[k][j];
}
}
}
}
}
where as input matrix you can enter
inE.txt
4 4
1 1 1 1
2 4 8 16
3 9 27 81
4 16 64 256
4 3
4.0 -3.0 4.0
-13.0 19.0 -7.0
3.0 -2.0 7.0
-1.0 1.0 -1.0
in unix like cmmd line execute the command:
$ java MatmultE < inE.txt > outE.txt
and you get the output
outC.txt
Matrix[2][2]
4.000 3.000
2.000 1.000
Matrix[2][2]
-0.500 1.500
1.000 -2.000
Matrix[2][2]
1.000 0.000
0.000 1.000
Matrix[3][4]
1.000 2.000 -2.000 0.000
-3.000 4.000 7.000 2.000
6.000 0.000 3.000 1.000
Matrix[4][2]
-1.000 3.000
0.000 9.000
1.000 -11.000
4.000 -5.000
Matrix[3][2]
-3.000 43.000
18.000 -60.000
1.000 -20.000
Matrix[4][3]
-7.000 15.000 3.000
-36.000 70.000 20.000
-105.000 189.000 57.000
-256.000 420.000 96.000
Matrix[4][3]
-7.00e+00 1.50e+01 3.00e+00
-3.60e+01 7.00e+01 2.00e+01
-1.05e+02 1.89e+02 5.70e+01
-2.56e+02 4.20e+02 9.60e+01
My code is super easy and works for any order of matrix
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(" Enter No. of rows in matrix 1 : ");
int arows = sc.nextInt();
System.out.println(" Enter No. of columns in matrix 1 : ");
int acols = sc.nextInt();
System.out.println(" Enter No. of rows in matrix 2 : ");
int brows = sc.nextInt();
System.out.println(" Enter No. of columns in matrix 2 : ");
int bcols = sc.nextInt();
if (acols == brows) {
System.out.println(" Enter elements of matrix 1 ");
int a[][] = new int[arows][acols];
int b[][] = new int[brows][bcols];
for (int i = 0; i < arows; i++) {
for (int j = 0; j < acols; j++) {
a[i][j] = sc.nextInt();
}
}
System.out.println(" Enter elements of matrix 2 ");
for (int i = 0; i < brows; i++) {
for (int j = 0; j < bcols; j++) {
b[i][j] = sc.nextInt();
}
}
System.out.println(" The Multiplied matrix is : ");
int sum = 0;
int c[][] = new int[arows][bcols];
for (int i = 0; i < arows; i++) {
for (int j = 0; j < bcols; j++) {
for (int k = 0; k < brows; k++) {
sum = sum + a[i][k] * b[k][j];
c[i][j] = sum;
}
System.out.print(c[i][j] + " ");
sum = 0;
}
System.out.println();
}
} else {
System.out.println("Order of matrix in invalid");
}
}
multiply 4x4 Matrixes
float[] mul(float[] l, float[] r) {
float[] res = new float[16];
for (int i = 0; i < 16; i++) {
int y = i / 4;
int x = i % 4;
res[i] = l[x] * r[y] +
l[x + 4] * r[y + 4] +
l[x + 8] * r[y + 8] +
l[x + 12] * r[y + 12];
}
return res;
}
import java.util.*;
public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C = new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for (int i = 0; i < B.length; i++) {
for (int j = 0; j < B.length; j++) {
B[i][j] = s.nextInt();
}
}
if (Cola == Rowb) {
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
C[i][j] = 0;
for (int k = 0; k < B.length; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
} else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
System.out.print(A[i][j] + "\t");
}
System.out.println();
}
*/
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
System.out.print(C[i][j] + "\t");
}
System.out.println();
}
}
}
#include <stdio.h>
int main()
{
int row = 2;
int col = 3;
int a[row][col];
int count = 1;
printf("Array A \n");
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
a[i][j] = count;
count++;
printf(" %d ", a[i][j]);
}
printf("\n");
}
int b[col][row];
printf("\nArray B \n");
for (int i = 0; i < col; i++)
{
for (int j = 0; j < row; j++)
{
b[i][j] = count;
count++;
printf(" %d ", b[i][j]);
}
printf("\n");
}
printf("\n A * B \n");
int c[row][col];
int mul = 1, plus = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < row; j++)
{
plus = 0;
for (int k = 0; k < col; k++)
{
mul = a[i][k] * b[k][j];
plus += mul;
}
c[i][j] = plus;
printf(" %d ", c[i][j]);
}
printf("\n");
}
}