Finding a row sums of a 2D array - java

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]

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

Adding each column inside a Jagged array not working

I have been recently working with 2D and Jagged Arrays and am trying to add each element in a row and each element inside a column. I got the code to print out the sum of each row, but am having difficulty with adding each column in the array.
Note: I tried doing sum += numbers[c][r]; but it is not working
import java.util.Arrays;
import java.io.*;
public class Homework{
public static void main(String[] args) {
int[][] numbers = { {3, 2, 5,},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8} };
//Adding each row in the array
int sum = 0;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
}
System.out.println("Sum of row: " + sum);
}
//Adding each column in the row
int sum2 = 0;
for(int r = 0; r < numbers.length; r++) {
sum2 = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum2 += numbers[c][r];
}
System.out.println("Sum of column: " + sum2);
}
}
}
Okay so you were sort of on the right track. Let me explain a way of thinking before I get into the code.
You have a non-square 2d Array and you want the total of each row and column. Row is simple, you've accomplished that already. Column is a little more difficult because since its non-square, you will run into ArrayOutOfBoundsExceptions because it tries to access a art of the array that doesn't exist.
To combat this, you need to know the max number of columns there are and then iterate through the array. BUT, you also need to be careful about that ArrayOutOfBoundsException, making sure to account for when the current column iteration is greater than the row length.
I added an int max to your row sum section, this way I don't have to iterate over the same info more than once.
After that, I replace c < numbers[r].length with 'max', since we need to iterate over X columns.
Then I iterate over the rows, since they are uniform and easily found by numbers.length.
So, a simple change to your code yields the results you need. See below.
int[][] numbers = {
{3, 2, 5},
{1, 4, 4, 8, 13},
{9, 1, 0, 2},
{0, 2, 6, 3, -1, -8}
};
int max = 0;
//Adding each row in the array
int sum;
for(int r = 0; r < numbers.length; r++) {
sum = 0;
for(int c = 0; c < numbers[r].length; c++) {
sum += numbers[r][c];
if(numbers[r].length > max){
max = numbers[r].length;
}
}
System.out.println("Sum of row: " + sum);
}
System.out.println("Max " + max);
//Adding each column in the row
int sum2;
for(int c = 0; c < max; c++) {
sum2 = 0;
for(int y = 0; y < numbers.length; y++){
if(numbers[y].length > c){
sum2 += numbers[y][c];
System.out.println(numbers[y][c]);
}
}
System.out.println("Sum of column: " + sum2);
}
}

Trouble with splitting an array into chunks

I have an array:
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
I'm trying to split it into a two-dimensional array with x amount of chunks, where all of the chunks have an equal length (in my case, 2), then assign each value of the original array to a corresponding index within the array. It would then increment the index of the chunk number and reset the index iterating through the individual arrays hit the length of one.
Problem is, the code I wrote to perform all that isn't outputting anything:
public class Debug
{
private static int[] array = {5, 2, 1, 6, 3, 7, 8, 4};
private static void chunkArray(int chunkSize)
{
int chunkNumIndex = 0;
int chunkIndex = 0;
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++)
{
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
while(chunkNumIndex < numOfChunks)
{
if (chunkIndex == chunkSize)
{
chunkNumIndex++;
chunkIndex = 0;
}
}
}
for(int i = 0; i < chunkNumIndex; i++)
{
for(int j = 0; j < chunkIndex; j++)
{
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
System.out.println();
}
}
public static void main(String args[])
{
chunkArray(2);
}
}
Could anyone be of assistance in debugging my program?
The problem is that you have an unnecessary while(chunkNumIndex < numOfChunks) which makes no sense. The if statement is sufficient to iterate your variables correctly:
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[chunkNumIndex][chunkIndex] = array[i];
chunkIndex++;
if (chunkIndex == chunkSize) {
chunkNumIndex++;
chunkIndex = 0;
}
}
Also, remember that the values of chunkNumIndex and chunkIndex are dynamic, so for the last for loops, use twoDimensionalArray.length and twoDimensionalArray[0].length instead:
for(int i = 0; i < twoDimensionalArray.length; i++) {
for(int j = 0; j < twoDimensionalArray[0].length; j++) {
System.out.printf("%5d ", twoDimensionalArray[i][j]);
}
}
You're making this unnecessarily hard, there is no need to keep counters for chunkIndex and chunkNumIndex, we can just div and mod i.
int numOfChunks = (array.length / chunkSize) + (array.length % chunkSize == 0 ? 0 : 1);
int[][] twoDimensionalArray = new int[numOfChunks][chunkSize];
for (int i = 0; i < array.length; i++) {
twoDimensionalArray[i / chunkSize][i % chunkSize] = array[i];
}
Something like this should already do the job.

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

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

Categories

Resources