How to multiply 2 dimensional arrays? Matrix Multiplication - java

So I have a code that will print a table of 2 dimensional arrays. The problem that I've run into is that I have absolutely no idea how to multiply and find the product of the arrays. Any help is appreciated. Thanks
public class MultiplyingArrays {
public static void main(String[] args) {
int firstarray[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
int secondarray[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
System.out.println("This is the first array");
display(firstarray);
System.out.println("This is the second array");
display(secondarray);
}
public static void display(int x[][]) {
for (int row = 0; row < x.length; row++) {
for (int column = 0; column < x[row].length; column++) {
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
}
The desired result would be:
-3 43
18 60
1 -20

int firstarray[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
int secondarray[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
/* Create another 2d array to store the result using the original arrays' lengths on row and column respectively. */
int [][] result = new int[firstarray.length][secondarray[0].length];
/* Loop through each and get product, then sum up and store the value */
for (int i = 0; i < firstarray.length; i++) {
for (int j = 0; j < secondarray[0].length; j++) {
for (int k = 0; k < firstarray[0].length; k++) {
result[i][j] += firstarray[i][k] * secondarray[k][j];
}
}
}
/* Show the result */
display(result);
P.S. Use proper naming convention.

import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the base of square matrix");
n=sc.nextInt();
int a[][]=new int[n][n];
int b[][]=new int[n][n];
int c[][]=new int[n][n];
System.out.println("Enter the elements of matrix a");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Enter the elements of matrix b");
for(int i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
b[i][j]=sc.nextInt();
}
}
System.out.println("Multiplying the matrices....");
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
System.out.println("the product is:");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print(c[i][j]+" ");
}
System.out.println();
}
}
}

for those who like methods:
import java.util.*;
public class MatmultD
{
private static Scanner sc = new Scanner(System.in);
public static void main(String [] args)
{
int a[][] = {{1, 2, -2, 0}, {-3, 4, 7, 2}, {6, 0, 3, 1}};
int b[][] = {{-1, 3}, {0, 9}, {1, -11}, {4, -5}};
int[][] c=multMatrix(a,b);
printMatrix(a);
printMatrix(b);
printMatrix(c);
}
public static int[][] readMatrix() {
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] result = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = sc.nextInt();
}
}
return result;
}
public static void printMatrix(int[][] 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("%4d " , mat[i][j]);
}
System.out.println();
}
System.out.println();
}
public static int[][] multMatrix(int a[][], int b[][]){//a[m][n], b[n][p]
if(a.length == 0) return new int[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;
int ans[][] = new int[m][p];
for(int i = 0;i < m;i++){
for(int j = 0;j < p;j++){
for(int k = 0;k < n;k++){
ans[i][j] += a[i][k] * b[k][j];
}
}
}
return ans;
}
}
and the output look like
Matrix[3][4]
1 2 -2 0
-3 4 7 2
6 0 3 1
Matrix[4][2]
-1 3
0 9
1 -11
4 -5
Matrix[3][2]
-3 43
18 -60
1 -20

Related

Need to find and store the duplicate numbers in a array in another array but dont know how to put the duplicate's in another array

I have found out the duplicate numbers in the array "a" but could not store the duplicate ones in another array "b". Any help much appreciated!
Here is my code:
public static void main(String[] args) {
int[] a = {1,2,3,3,5,6,1,7,7};
int[] b={};
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i]==(a[j])){
System.out.println(a[j]);
}
}
}
Because the length of result is not know, I would like to use a ArrayList instead of an array :
int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7};
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j] && !b.contains(a[j])) {
b.add(a[j]);
System.out.println(a[j]);
}
}
}
System.out.println(b);//result : [1, 3, 7]
You can try finding duplicates in an array using collections framework too:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
int[] a = {1,2,3,3,5,6,1,7,7};
Set<Integer> set=new HashSet<Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i:a) {
if(!set.add(i)) {
list.add(i);
}
}
int[] b=new int[list.size()];
for (int i=0;i<list.size();i++) {
b[i] =list.get(i);
}
}
}
Here I have used the fact that sets do not allow duplicate and if set.add returns false, that means that element is already available in the set
We cannot change the size of Array once it is initialized. Here we do not know how many duplicates item will be in the Array.
EDIT -- This might be a better solution, my earlier solution was throwing ArrayIndexOutOfBoundException as indicated by #YCF_L --
import java.util.Arrays;
public class T {
public static void main(String[] args) {
//int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7}; //Set-1, provided by #YCF_L
int[] a = {1,1,3,3,5,6,1,7,7}; //Set-2, provided by OP
int[] b = {};
for (int i=0, k=0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i] == a[j]){
System.out.println(a[j]);
k = k+1;
int[] p = new int[k];
for(int x=0; x < b.length; x++) {
p[x] = b[x];
}
p[k-1] = a[i];
b = p;
}
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(removeDuplicates(b)));
}
public static int[] removeDuplicates(int[] a) {
boolean[] bArr = new boolean[1000];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (!bArr[a[i]]) {
bArr[a[i]] = true;
j++;
}
}
int[] b = new int[j];
int c = 0;
for (int i = 0; i < bArr.length; i++) {
if (bArr[i]) {
b[c++] = i;
}
}
return b;
}
}
Output with Set-1 :
[1, 3, 7]
[1, 3, 7]
Output with Set-2 :
[1, 1, 1, 3, 7]
[1, 3, 7]

Find a sum pair in array with duplicates in O(n)

Array with duplicates [4,4,1]. Find pairs with sum 5 in O(n).
Expected output (4,1) and (4,1) and count is 2.
Approach#1:
Using HashSet:
public static int twoSum(int[] numbers, int target) {
HashSet<Integer> set = new HashSet<Integer>();
int c = 0;
for(int i:numbers){
if(set.contains(target-i)){
System.out.println(i+"-"+(target-i));
c++;
}
set.add(i);
}
return c;
}
Output is 1.
Approach #2 as stated in this link:
private static final int MAX = 100000;
static int printpairs(int arr[],int sum)
{
int count = 0;
boolean[] binmap = new boolean[MAX];
for (int i=0; i<arr.length; ++i)
{
int temp = sum-arr[i];
if (temp>=0 && binmap[temp])
{
count ++;
}
binmap[arr[i]] = true;
}
return count;
}
Output 1.
However the O(nlog n) solution is using sorting the array:
public static int findPairs(int [] a, int sum){
Arrays.sort(a);
int l = 0;
int r = a.length -1;
int count = 0;
while(l<r){
if((a[l] + a[r]) == sum){
count ++;
System.out.println(a[l] + " "+ a[r]);
r--;
}
else if((a[l] + a[r])>sum ){
r--;
}else{
l++;
}
}
return count;
}
Can we get the solution in O(n)?
You can use your second approach - just change boolean to int:
public static void main(String[] args) {
System.out.println(printPairs(new int[]{3, 3, 3, 3}, 6)); // 6
System.out.println(printPairs(new int[]{4, 4, 1}, 5)); // 2
System.out.println(printPairs(new int[]{1, 2, 3, 4, 5, 6}, 7)); // 3
System.out.println(printPairs(new int[]{3, 3, 3, 3, 1, 1, 5, 5}, 6)); // 10
}
public static int printPairs(int arr[], int sum) {
int count = 0;
int[] quantity = new int[sum];
for (int i = 0; i < arr.length; ++i) {
int supplement = sum - arr[i];
if (supplement >= 0) {
count += quantity[supplement];
}
quantity[arr[i]]++; // You may need to check that arr[i] is in bounds
}
return count;
}
you can try this also
Map<Integer, List> map = new HashMap<>();
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(k - arr[i])) {
count += map.get(k - arr[i]).size();
}
List<Integer> test = map.getOrDefault(arr[i], new ArrayList<>());
test.add(i);
map.put(arr[i], test);
}
return count;
Here is an O(N) Time & Space approach using HashMap.
class Solution
{
static int getPairsCount(int[] arr, int n, int target)
{
HashMap<Integer,Integer> map = new HashMap<>();
int pairs=0;
for (int i=0; i<n; i++)
{
if (map.containsKey(target - arr[i]))
{
pairs += map.get(target - arr[i]);
for (int j=1; j<=map.get(target - arr[i]); j++)
System.out.print("(" +(target-arr[i])+ "," +arr[i]+ ") ");
}
map.put(arr[i] , map.getOrDefault(arr[i],0)+1);
}
return pairs;
}
public static void main (String [] args)
{
int target = 5;
int [] input = {4, 4, 1};
System.out.println(getPairsCount(input , input.length , target));
target = 10;
input = new int [] {1, 6, 3, 2, 5, 5, 7, 8, 4, 8, 2, 5, 9, 9, 1};
System.out.println(getPairsCount(input , input.length , target));
}
}
Output:
2 (Pairs)
(4,1) (4,1)
13 (Pairs)
(5,5) (3,7) (2,8) (6,4) (2,8) (8,2) (8,2) (5,5) (5,5) (1,9) (1,9) (9,1) (9,1)

Sum of int[][] rows as int[] (Java)

I'm trying to take the sum of each row in a 2d array and store the values in a new array. Right now sum[] is only returning the values stored in the first row. Please help me understand what I'm missing here.
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[row] += matrix[col][row];
}
}
return sum;
}
Since you use Java 8 you can use:
return Arrays.stream(matrix) // Stream<int[]>
.mapToInt(row -> Arrays.stream(row).sum()) // IntStream
.toArray(); // int[]
Following code works for 2D arrays of different size as well.
public static void main(String[] args) {
int[][] matrix = {
{2, 3, 4, 5, 6, 7, 8, 9}, // 8 elements
{2, 1, 4, 5, 7, 2, 86} // 7 elements
};
int[] sum = rowSum(matrix);
for (int i : sum) {
System.out.println(i);
}
}
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum[i] = sum[i] + matrix[i][j];
}
}
return sum;
}
simple
public static int[] rowSum(int[][] matrix) //find sum of digits in given row
{
int[] sum = new int[6];
ARRAY_LENGTH = 6;
for (int col = 0; col < ARRAY_LENGTH; col++)
{
for (int row = 0; row < ARRAY_LENGTH; row++)
{
sum[col] += matrix[col][row];
}
}
}
careful with ARRAY_LENGTH

returning an array of n numbers repeated into another array

Basically i have to return an array of n numbers repeated in an array into another array of length m.
my code so far:
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count = 0;
for(int j = 0; j < a.length; j++)
for(int i = 0; i < m.length; i++)
if( i == a[j]){
m[i] = count++;
}
}
return m;
} public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
Std.Out.println(i + "->" + b[i]);
} } }
this is the output im supposed to get
0->0
1->3
2->2
3->2
4->4
5->2
6->0
7->3
8->3
9->3
10->4
11->4
but im getting
0->0
1->21
2->16
3->23
4->27
5->29
6->0
7->20
8->25
9->15
10->28
11->22
what am i doing wrong?
I am not going to give you a different solution, but rather to show the mistakes in your code. If we go with the logic in your code, you have few mistakes:
1) count should be reset to 0 after first loop. Otherwise you will sum up the counts from the previous iterations.
2) count++ should be before the assignment, otherwise it will first assign and then increment. Or you could use ++count.
3) The first loop should be over i.
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
int count;
for(int i = 0; i < m.length; i++) {
count =0;
for(int j = 0; j < a.length; j++)
if( i == a[j]){
count++;
m[i] = count;
}
}
return m;
}
Regards.
This should solve it and do the job!
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int j = 0; j < a.length; j++) {
m[a[j]] += 1;
}
return m;
}
public static void main(String[] args) {
int[] a = {7, 4, 9, 1, 10, 11, 11, 1, 5, 8, 4, 2, 9, 4, 3, 9,
2, 10, 11, 7, 7, 1, 11, 3, 8, 8, 10, 4, 10, 5};
int[] b = frequency(a, 12);
for (int i = 0; i < b.length; i++) {
System.out.println(i + "->" + b[i]);
}
}
}
public class Histogram {
public static int[] frequency(int[] a, int M) {
int[] m = new int[M];
for(int i = 0; i < a.length; i++) //loop through a
if( i < M) //number check
m[a[i]]++; //add one to m at index a[i]
return m;
}
}
this is the right code for the method frequency, also checks to see if the number is in range.

Trying to find the sum of the last column

public class arsum
{
static int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
public int[] summing(int[][] array)
{
int index = 0;
int a[] = new int[array[index].length];
for (int i = 0; i < array[0].length; i++)
{
int sum = 0;
for (int j = 0; j < array.length; j++)
{
sum += array[j][i];
}
a[index] = sum;
System.out.println(sum);
}
return a;
}
public static void main(String[] args) {
new arsum().summing(myarray);
}
}
At the moment it prints out all 4 column sums, however I only want the last sum. I cannot figure out how to code it properly for any general array.
I am new to coding and have not totally figured everything out yet.
Try,
int[][] myarray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {1, 2, 3, 4}};
int sum = 0;
for (int nums[] : myarray) {
sum += nums[nums.length - 1];
}
System.out.println(sum);
you can also use array indexing to print sum of last column as below:-
public static int summing(int[][] array)
{
int row = array.length;
int sum = 0;
for (int i = row - 1; i > row - 2; i--) {
int col = myarray[i].length;
for (int j = 0; j < col; j++) {
sum += array[i][j];
}
System.out.println(sum);
}
return sum;
}

Categories

Resources