Trying to find the sum of the last column - java

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;
}

Related

Getting the Elements that has duplicates in an int array Java

This post - "Java + Count duplicates from int array without using any Collection or another intermediate Array", was also a sample exercise in my book at school, but what I want to do is get the elements that has duplicates without sorting it.
What I did is I removed the duplicates of arrays first, to get only the unique elements and then I compare it to the original array and count how many times the element has been found. But the problem is it doesn't print the correct elements which has duplicates.
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
the correct output should be: 7, 1, 4
but instead it outputs: 7, 6, 1
This is my codes:
//method for removing duplicates
public static int[] removeDuplicates(int[] n) {
int limit = n.length;
for(int i = 0; i < limit; i++) {
for(int j = i + 1; j < limit; j++) {
if(n[i] == n[j]) {
for(int k = j; k < limit - 1; k++) {
n[k] = n[k + 1];
}
limit--;
j--;
}
}
}
int[] uniqueValues = new int[limit];
for(int i = 0; i < uniqueValues.length; i++) {
uniqueValues[i] = n[i];
}
return uniqueValues;
}
//method for getting elements that has duplicates
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
int count = 0;
int limit = u.length;
for(int i = 0; i < u.length; i++) {
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
//main
public static void main(String[] args) {
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
//printing original values
System.out.print(Arrays.toString(num));
System.out.println();
int[] a = getDuplicatedElements(num);
System.out.print("Elements with Duplicates: " + Arrays.toString(a));
}
What's the error in my codes here? Please help thanks...
You have two issues:
public static int[] getDuplicatedElements(int[] n) {
int[] nCopy = n.clone();
int[] u = removeDuplicates(nCopy);
System.out.println ("unique " + Arrays.toString (u));
int count = 0;
int limit = u.length;
for(int i = 0; i < limit; i++) { // you must use limit instead of u.length
// in order for the loop to terminate
for(int j = 0; j < n.length; j++) {
if(u[i] == n[j]) {
count++;
}
}
if(count == 1) {
for(int k = i; k < limit - 1; k++) {
u[k] = u[k + 1];
}
limit--;
i--; // you must decrement i after you find a unique element in u
// otherwise you'll be skipping elements in the u array
}
count = 0;
}
int[] duplicated = new int[limit];
for(int i = 0; i < duplicated.length; i++) {
duplicated[i] = u[i];
}
return duplicated;
}
With those fixes, you'll get the expected output:
Elements with Duplicates: [7, 1, 4]
It's fairly simple when using a stream
int[] num = {7, 2, 6, 1, 4, 7, 4, 5, 4, 7, 7, 3, 1};
List<Integer> list = Arrays.stream(num).boxed().collect(Collectors.toList());
list.stream().filter(i -> Collections.frequency(list, i) > 1)
.collect(Collectors.toSet()).forEach(System.out::println);

Java matching arrays

The method which takes two integer arrays. The method returns an integer array containing all the elements in array int[]a that are also present in array int[]b in their original sequential order in int[]a.
This is what it should output :
input: {1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 2, 10}, {3, 2, 7, 12, 3, 9, 5, 2}
output: {2, 3, 5, 7, 3, 9, 2}
input: {4, 7, 1, 6, 9, 2, 3, 1}, {8, 5, 2, 1, 9, 4}
output: {4, 1, 9, 2, 1}
I tried something like this just to test it out to get my head around it but I still couldn't.
public static void arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i <= s1.length; i++) {
for (int j = 0; j <= s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
break;
}
System.out.println(storage);
}
Test cases:
int [] m1 = {1, 2, 3, 4, 5, 6, 7, 3, 8, 9, 2, 10};
int [] m2 = {3, 2, 7, 12, 3, 9, 5, 2};
System.out.println(Arrays.toString(arraysMatching(m1, m2)));
Should print out [2, 3, 5, 7, 3, 9, 2]
To add to Codors answer, have the method return int[]:
public static int[] arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<>();
//for (int i = 0; i <= s1.length; i++) {
//wrong. change <= to < or better:
for (int i : s1) {
//for (int j = 0; j <= s2.length; j++) {
//wrong. change <= to < or better:
for (int j : s2) {
if (j == i) {
storage.add(j);
break;
}
}
}
//if you can use streams do
//return storage.stream().mapToInt(i->(int)i).toArray();
//alternatively
int[] returnArray = new int[storage.size()];
for(int i=0; i< storage.size(); i++) {
returnArray[i]=storage.get(i);
}
return returnArray;
}
So you can use it with System.out.println(Arrays.toString(arraysMatching(m1, m2)));
To my understanding, the second break statement terminates the outer loop too early; furthermore, the indexing goes one step too far in both loop termination conditions. Change the implementation as follows.
public static void arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
System.out.println(storage);
}
Edit:
If the result is not to be printed but to be returned, the signature and the body have to be changed as follows.
public static ArrayList<Integer> arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
return storage;
}
Edit:
If the return type is required to be Integer[], the implementation has to be changed as follows.
public static Integer[] arraysMatching(int[] s1, int[] s2) {
ArrayList<Integer> storage = new ArrayList<Integer>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
int[] result = new int[storage.size()];
result = storage.toArray(result);
return result;
}
Edit:
If the return type is required to be int[] and no 'fancy stuff' for result conversion is desired, the code has to be changed as follows.
public static int[] arraysMatching(int[] s1, int[] s2) {
ArrayList<int> storage = new ArrayList<int>();
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s2.length; j++) {
if (s2[j] == s1[i]) {
storage.add(s2[j]);
break;
}
}
}
int[] result = new int[storage.size()];
for (int k = 0; k < storage.length(); k++) {
result[k] = storage.get(k);
}
return result;
}

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.

How to multiply 2 dimensional arrays? Matrix Multiplication

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

Categories

Resources