Sum of int[][] rows as int[] (Java) - 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

Related

Finding a row sums of a 2D array

I want to find the sum of the first row and second row of a 2D array of integers. This is my code and is there any way I can make this code shorter?
//creating 2D array for integers
int[][] num = {{1, 2, 3}, {4, 5, 6}};
int sum1 = 0;
int sum2 = 0;
//sum for first row
for (int a = 0; a == 0; a++) {
for (int b = 0; b <= 2; b++) {
sum1 += num[a][b];
}
System.out.println(sum1);
}
//sum for second row
for (int a = 1; a == 1; a++) {
for (int b = 0; b <= 2; b++) {
sum2 += num[a][b];
}
System.out.println(sum2);
}
Output is:
6
15
You can use streams to get an array of row sums of a 2d array as follows:
int[][] num = {{1, 2, 3}, {4, 5, 6}};
int[] sum = Arrays.stream(num)
.map(Arrays::stream)
.mapToInt(IntStream::sum)
.toArray();
System.out.println(Arrays.toString(sum)); // [6, 15]
Yes,
int[][] num = {{1, 2, 3}, {4, 5, 6}};
int sum1 = 0;
int sum2 = 0;
//sum for first row and second row
for (int a = 0; a <= 1; a++) {
for (int b = 0; b <= 2; b++) {
if (a == 0)
sum1 += num[a][b];
else
sum2 += num[a][b];
}
}
System.out.println(sum1); // 6
System.out.println(sum2); // 15
This may help you:
int[][] num = {{1, 2, 3}, {4, 5, 6}};
for (int a = 0; a <= 1; a++) {
int sum1 = 0;
for (int b = 0; b <= 2; b++) {
sum1 += num[a][b];
}
System.out.println(sum1);
}
You could use the Streams API:
import java.util.Arrays;
import java.util.stream.IntStream;
int[][] num = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
// sum of all elements in the 2D array
int sum = Arrays.stream(num).mapToInt(a -> IntStream.of(a).sum()).sum();
This sums all elements of the 2D array. This way your code sums the entire grid even if you add more rows or add more elements to each row.
If you need the sum of each row separately, consider this:
import java.util.stream.IntStream;
int[][] num = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
// sum of the first row
int sum1 = IntStream.of(num[0]).sum();
// sum of the second row
int sum2 = IntStream.of(num[1]).sum();
You can think about 2D array as an array of arrays.
You can simply iterate over the "big array" (lets call the index i) and then take the array on the i place and iterate over him (lets call the index j).
Now you can simply sum up the value on place [i][j] with the current value of a 0 initialized variable (lets call it sum).
in java:
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; i++)
sum += array[i][j];
}
// Output: 21
Or if you want to print only the sub arrays sum you can print the sum and initialize it when the second loop finished:
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; i++)
sum += array[i][j];
System.out.println(sum);
sum = 0;
}
// Output:
// 6
// 15
Because we're going to go through all the elements, in terms of time, O(n) is the optimal time complexity.
int sum1 = 0;
int sum2 = 0;
//sum for first row
for (int b = 0; b <= 2; b++) {
sum1 += num[0][b];
}
System.out.println(sum1);
//sum for second row
for (int b = 0; b <= 2; b++) {
sum2 += num[1][b];
}
System.out.println(sum2);
The outer loop in both instances is redundant, since it basically only deals as a variable declaration & initialization. This loop is not needed since it is only run once anyways.
You should also not use fixed sizes for your loops, as this will break your code once you alter the size of your array.
Also, I would suggest you use an array to store the sum for each row.
Example with all the suggestions:
public static void main(String[] args) {
int[][] nums = {{1, 2, 3}, {4, 5, 6}};
// hold the sum of each row in an array
int[] sums = new int[nums.length];
// loops shouldn't use fixed sizes, they
// should run according to the arrays size
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; j++) {
// for each row, calculate the sum
// and store it in the sum array
sums[i] += nums[i][j];
}
}
System.out.println(Arrays.toString(sums));
}
Output:
[6, 15]

Transposing matrices in Java

I think I am missing something fundamental here about Java, I am not sure why my code below do not work, my steps:
the input is a 2x2 matrix,
copy the original matrix,
loop through rows then column,
assign original matrix's column values to the rows of the transpose matrix.
static void transpose(int[][] matrix) {
int[][] temp = matrix.clone();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix[i][j] = temp[j][i];
}
}
}
The problem is use the function clone() because that will create a new matrix sharing only row arrays.
Using the same code style, that works:
int[][] temp = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
temp[i][j] = matrix[j][i];
}
}
Note that, as temp is an empty matrix, the comparsion will be temp = matrix.
So this works for a simple 2x2 matrix, but if you need other dimensions, instead of
int[][] temp = new int[2][2];
Use
int[][] temp = new int[matrix[0].length][matrix.length];
By the way, update the reference memory of the matrix is not a good practice. I think your method should return temp matrix.
An entire update, a better method could be this one. Is almost the same you have but it can accept diferent lengths.
public static int[][] transpose(int [][] matrix){
int[][] temp = new int[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
temp[j][i] = matrix[i][j];
}
}
return temp;
}
You can use IntStream instead of for loop:
public static void main(String[] args) {
int[][] m1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int[][] m2 = transpose(m1);
Arrays.stream(m2).map(Arrays::toString).forEach(System.out::println);
// [1, 4, 7]
// [2, 5, 8]
// [3, 6, 9]
}
static int[][] transpose(int[][] matrix) {
return IntStream.range(0, matrix.length).mapToObj(i ->
IntStream.range(0, matrix[i].length).map(j ->
matrix[j][i]).toArray())
.toArray(int[][]::new);
}

How to add elements from a list to a two-dimensional array?

I have a list of ints that I need to add to a two-dimensional array.
ArrayList<Integer> myList = new ArrayList<Integer>(size);
//Generation
if(size % 2 != 0) {
System.out.println("need nombre pair");
} else {
int x = 0;
while (x != 2) {
for (int i = 0; i >= size/2; i++) {
int n = (int)Math.random() * 10;
if(!myList.contains(n))
myList.add(n);
}
x++;
}
}
Collections.shuffle(myList);
Once my list is shuffled, I want to add all the ints to a two-dimensional array (int[][]). How do I do this?
Here's a method that will generate a 2D array that meets your requirements:
private static int[][] makeArray(int columns, int rows) {
int totalItems = rows * columns;
if (totalItems % 2 != 0) {
throw new IllegalArgumentException("Must be an even number of cells.");
}
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < totalItems / 2; i++) {
numbers.add(i);
numbers.add(i);
}
Collections.shuffle(numbers);
Iterator<Integer> iterator = numbers.iterator();
int[][] result = new int[columns][rows];
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
result[x][y] = iterator.next();
}
}
return result;
}
Here's a small main method to test it:
public static void main(String[] args) throws Exception {
int[][] array = makeArray(3, 4);
for (int i = 0; i < 3; i++) {
System.out.println(Arrays.toString(array[i]));
}
}
Example output:
[0, 5, 1, 0]
[3, 1, 5, 2]
[4, 3, 2, 4]
You could split your list into multiple subLists and convert those into arrays, one for each column of the table:
Integer[][] table = new Integer[width][];
for (int x = 0; x < width; x++) {
table[x] = myList.subList(width * x, width * x + height).toArray(new Integer[height]);
}

Adding the columns of a jagged 2D array

I've looked all over for a good answer, but I was surprised I couldn't find one that accomplished quite what I'm trying to do. I want to create a method that finds a columns sum in a jagged 2D array, regardless of the size, whether it's jagged, etc. Here is my code:
public static int addColumn(int[][] arr, int x) {
int columnSum = 0;
int i = 0;
int j = 0;
int numRows = arr.length;
//add column values to find sum
while (i < numRows) {
while (j < arr.length) {
columnSum = columnSum + arr[i][x];
j++;
i++;
}
}//end while loop
return columSum;
}
So, for example, consider I have the following array:
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
I want to be able to pass x as 2, and find the sum for Column 3 which would be 9. Or pass x as 3 to find Column 4, which would simply be 8. My code is flawed as I have it now, and I've tried about a hundred things to make it work. This is a homework assignment, so I'm looking for help to understand the logic. I of course keep getting an Out of Bounds Exception when I run the method. I think I'm overthinking it at this point since I don't think this should be too complicated. Can anyone help me out?
I think that your second while loop is making your sum too big. You should only have to iterate over the rows.
while (i < numRows) {
if (x < arr[i].length) {
columnSum += arr[i][x];
}
++i;
}
In Java 8, you can use IntStream for this purpose:
public static int addColumn(int[][] arr, int x) {
// negative column index is passed
if (x < 0) return 0;
// iteration over the rows of a 2d array
return Arrays.stream(arr)
// value in the column, if exists, otherwise 0
.mapToInt(row -> x < row.length ? row[x] : 0)
// sum of the values in the column
.sum();
}
public static void main(String[] args) {
int[][] arr = {{10, 12, 3}, {4, 5, 6, 8}, {7, 8}};
System.out.println(addColumn(arr, 2)); // 9
System.out.println(addColumn(arr, 3)); // 8
System.out.println(addColumn(arr, 4)); // 0
System.out.println(addColumn(arr, -1));// 0
}
I saw the codes above. None of it is the adequate answer since posting here the code which meets the requirement. Code might not look arranged or optimized just because of the lack of time. Thanks.... :)
package LearningJava;
import java.util.Scanner;
public class JaggedSum {
public static void main(String[] args) {
int ik = 0;
int ij = 0;
Scanner scan = new Scanner(System.in);
int p = 0;
int q = 0;
int[][] arr = new int[2][];
System.out.println("Enter the value of column in Row 0 ");
p = scan.nextInt();
System.out.println("Enter the value of column in Row 1 ");
q = scan.nextInt();
arr[0] = new int[p];
arr[1] = new int[q];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scan.nextInt();
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
if (arr[1].length > arr[0].length) {
int[] columnSum = new int[arr[1].length];
int x;
for (x = 0; x < arr[0].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ik = arr[0].length;
for (int j = ik; j < arr[1].length; j++) {
columnSum[j] = arr[1][j];
System.out.println(columnSum[j]);
}
} else {
int[] columnSum = new int[arr[0].length];
int x;
for (x = 0; x < arr[1].length; x++) {
columnSum[x] = arr[0][x] + arr[1][x];
System.out.println(columnSum[x]);
}
ij = arr[1].length;
for (int j = ij; j < arr[0].length; j++) {
columnSum[j] = arr[0][j];
System.out.println(columnSum[j]);
}
}
}
}

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