Adding the columns of a jagged 2D array - java

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

Related

Compare and count in two arrays not in same order - Java

I need to count how many of the same digits are in the code vs. guess.
If code = [1, 2, 5, 6] and guess = [4, 1, 3, 2], it should return 2.
I can't directly change the parameter arrays, so I first created new arrays, sorted, then looped through to find how many are the same in both. The issue is that it returns 4 no matter what.
public static int digits(int[] code, int[] guess) {
int[] sortedCode = new int[code.length];
int[] sortedGuess = new int[guess.length];
int digits = 0;
for (int i = 0; i < code.length; i++) {
sortedCode[i] = code[i];
sortedGuess[i] = guess[i];
}
Arrays.sort(sortedCode);
Arrays.sort(sortedGuess);
for (int i = 0; i < code.length; i++) {
if (sortedGuess[i] == sortedCode[i]) {
digits++;
}
}
return digits;
As #Icarus mentioned in the comments, "you're comparing index to index when you should compare index to every index".
public static int getCorrectDigits(int[] code, int[] guess) {
int correctDigits = 0;
if (code.length != guess.length) {
throw new IllegalArgumentException("Different lengths");
}
for (int x = 0; x<code.length; x++){
for (int y = 0; y<guess.length; y++){
if (code[x] == guess[y]){
correctDigits++;
}
}
}
return correctDigits;
}
You can also convert the traditional for loop to an enhanced for loop.
for (int j : code) {
for (int i : guess) {
if (j == i) {
correctDigits++;
}
}
}

Get the maximum summation of 2D array

There is a 2D array. int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}} . I want to get summation of each columns and get the maximum number. Finally it should be returned {5,7,8,9} . Because it has the maximum summation. I have mentioned i tried code below and it not return correct value. Help me to solve this
Your k is supposed to track the index with the greatest sum. So when you are resetting max you need to say k=i. You said i=k by mistake. Changing it makes your program run as desired.
EDIT: There was once code in the original question, to which this solution referred.
If the max column is expected, then I might have a solution:
import java.util.Arrays;
public class ArrayTest {
public static void main(String args[]) {
/*
* 1 3 4 1
* 5 7 8 9
* 6 1 2 1
*
*/
int[][] arr = {{1, 3, 4, 1}, {5, 7, 8, 9}, {6, 1, 2, 1}};
int m = arr.length;
int n = arr[0].length;
int[] arr2 = new int[n];
int p = 0;
int[][] colArray = new int[n][m];
for (int i = 0; i < n; i++) {
int[] arr_i = new int[m];
//System.out.println("i = " + i);
//System.out.println("p = " + p);
int sum = 0;
for (int j = 0; j < m; j++) {
arr_i[j] = arr[j][p];
sum += arr_i[j];
}
//System.out.println("Col: " + p + " : " + Arrays.toString(arr_i));
colArray[i] = arr_i;
arr2[p] = sum;
p++;
}
System.out.println("Sum: " + Arrays.toString(arr2));
int k = 0;
int max = arr2[0];
for (int i = 0; i < 3; i++) {
if (arr2[i] > max) {
max = arr2[i];
k = i;
}
}
System.out.println("Column index for max: " + k);
System.out.println("Column: " + Arrays.toString(colArray[k]));
}
}
Output:
Sum: [12, 11, 14, 11]
Column index for max: 2
Column: [4, 8, 2]
I recommend you find a way to break down your problem into smaller parts, solve each part with a function, then combine everything into a solution.
Example solution below:
public class Main {
public static long sum(int[] a){
long sum = 0;
for (int i : a) {
sum = sum + i;
}
return sum;
}
public static int[] withMaxSumOf(int[][] as){
// keep one sum for each array
long[] sums = new long[as.length];
// calculate sums
for (int i = 0; i < as.length; i++) {
int[] a = as[i];
sums[i] = sum(a);
}
// find the biggest one
int maxIndex = 0;
long maxSum = sums[0];
for (int i=1;i<sums.length;i++){
if (sums[i] > maxSum){
maxSum = sums[i];
maxIndex = i;
}
}
// return array that had biggest sum
return as[maxIndex];
}
public static void main(String[] args){
int[][] arr= {{1,3,4,1},{5,7,8,9},{6,1,2,1}};
// find the one with max sum
int[] max = withMaxSumOf(arr);
// print it
for (int i = 0; i < max.length; i++) {
int x = max[i];
if (i > 0) System.out.print(", ");
System.out.print(x);
}
System.out.println();
}
}
I think this might be your problem:
for(int i=0;i<3;i++) {
if(arr2[i]>max) {
max=arr2[i];
i=k;
}
}
I think that i=k really needs to be k=i.
Note also that it's worthwhile using better variable names. index instead of i, for instance. What is k? Call it "indexForHighestSum" or something like that. It doesn't have to be that long, but k is a meaningless name.
Also, you can combine the summation loop with the find-highest loop.
In the end, I might write it like this:
public class twoDMax {
public static void main(String args[]) {
int[][] arr= { {1,3,4,1}, {5,7,8,9}, {6,1,2,1} };
int indexForMaxRow = 0;
int previousMax = 0;
for(int index = 0; index < 4; ++index) {
int sum = 0;
for(int innerIndex = 0; innerIndex < 4; ++innerIndex) {
sum += arr[index][innerIndex];
}
if (sum > previousMax) {
previousMax = sum;
indexForMaxRow = index;
}
System.out.println(indexForMaxRow);
for(int index = 0; index < 4; ++index) {
System.out.println(arr[indexForMaxRow][index]);
}
}
}
I did a few other stylish things. I made use of more obvious variable names. And I am a little nicer about whitespace, which makes the code easier to read.
public static void main( String args[] ) {
int[][] arr = { { 1, 3, 4, 1 }, { 5, 7, 8, 9 }, { 6, 1, 2, 1 } };
int indexOfMaxSum = 0;
int maxSum = 0;
for ( int i = 0; i < arr.length; i++ ) {
int[] innerArr = arr[ i ]; // grab inner array
int sum = 0; // start sum at 0
for ( int j : innerArr ) {
// iterate over each int in array
sum += j; // add each int to sum
}
if ( sum > maxSum ) {
// if this sum is greater than the old max, store it
maxSum = sum;
indexOfMaxSum = i;
}
}
System.out.println( String.format( "Index %d has the highest sum with a sum of %d", indexOfMaxSum, maxSum ) );
int [] arrayWithLargestSum = arr[indexOfMaxSum]; // return me
}

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.

trouble with creating a method that returns the average of each column of a 2d array (this is in java)

Im having trouble creating this method because i just started on arrays and now i have to create a method that takes as an input an 2d array of inters and returns one single array that contains the average for each column? can anyone help?
public class Assigment4 {
public static void main(String[] args) {
int[][] a = new int[5][5];
a[0][0] = 1; //rows
a[0][1] = 2;
a[0][2] = 3;
a[0][3] = 4;
a[0][0] = 1; //columns
a[1][0]= 2;
a[2][0] = 3;
a[3][0] = 4;
double []summ =(averageForEachColumn(a));
}
public static double [] averageForEachColumn (int [][] numbers){
double ave [] = new double[numbers[0].length];
int count=0;
for (int i = 0; i < numbers[0].length; i++){
double sum = 0;
count= count+1;
for (int j = 0; j < numbers.length; j++){
count= count +1;
sum += numbers[j][i];
}
ave[i] = sum/count;
System.out.println (sum);
}
return ave;
}
}
Your count should be reset to 0 before the inner loop.
count= count+1; // change this to count = 0;
for (int j = 0; j < numbers.length; j++){
You haven't populated most of the values in the 2d array. There are 16 total values, you have populated 7 of them (one of them twice).
Get rid of count altogether, you don't need it.
Change:
ave[i] = sum/count;
To:
ave[i] = sum/a[i].length;
This is a simplified example of a 2x4 array. You can add more values at you leisure.
public static void main(String[] args)
{
int[][] array = {{1, 2, 3, 4},{5, 6, 7, 8}};
for(int col = 0; col < 4; col++)
{
double sum = 0;
int row = 0;
while (row < array.length)
{
sum+=array[row++][col];
}
System.out.println("Average of values stored in column " + col + " is " + sum / array.length);
}
}
Of course, you can add the result of sum/array.length to an array of averages instead of just displaying it.

Finding differences in a array

I'm not sure how to set the differences to store in the array differences. The numbers stored should be 5-(1+2+3), 7-(1,2,4), 8-(3,5,9) : the output should be differences[0]= 1, differences[1] = 0, differences[2] = 9
import java.util.Scanner;
public class Main {
public static int[][] Array = { { 5, 1, 2, 3 }, { 7, 1, 2, 4 }, { 8,3,5,9 } }; //My 2D array//
int [] differences = new int [3];
public static int[] Sum(int[][] array) {
int index = 0; //setting the index to 0//
int temp[] = new int[array[index].length]; //making a temperary variable//
for (int i = 0; i < array.length; i++) {
int sum = 0;
for (int j = 1; j < array[i].length; j++) {
sum += array[i][j]; //going to add the rows after the first column//
}
temp[index] = sum;
for(int a = 0; a<differences.length; a++){
if(sum != array[index][0])
sum -= array[i][j];
System.out.println("the first integer " + array[index][0] + " the answer is " + sum); //going to print out the first integer each row and print out the sum of each row after the first column//
index++; //index is going to increment//
}
return temp;
}
public static void main(String[] args) {
new Main().Sum(Array);
}
}
Output:
the first integer 5 the answer is 6
the first integer 7 the answer is 7
the first integer 8 the answer is 17
Why do you want to complicate the task of yours when it is this simple? :)
public int[] Sum(int[][] array)
{
int sum;
for(int i = 0; i < Array.length; i++)
{
sum = Array[i][0] * -1;
for(int j = 1; j < Array[i].length; j++)
{
sum += Array[i][j];
}
differences[i] = sum;
}
return differences;
}
If I understand your problem correctly, I think that you want to put a
differences[i] = Array[i][0] - sum
somewhere in your code

Categories

Resources