Sum Specified Column Jagged Array - arrays

My homework assignment is asking to output the sum of a specified column of a Jagged 2D Array. I've seen other solutions that show how to get the sum of ALL columns, but not a specific one. The issue I'm running into is that I get a java.lang.ArrayIndexOutOfBoundsException if a column is entered and no element exists in a row of the 2D array.
// returns sum of specified column 'col' of 2D jagged array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
for (int j = 0; j < array[col].length; j++) {
sum += array[j][col];
}
return sum;
} // end columnSum()
Example: Ragged Array Input (class is named RaggedArray)
int[][] ragArray = { {1,2,3},
{4,5},
{6,7,8,9} };
System.out.println(RaggedArray.columnSum(ragArray, 2));
This obviously gives me an ArrayIndexOutOfBoundsException, but I don't know how to fix it if a specified column is asked for as an argument. Any ideas? I appreciate any help or suggestions!

In your loop, do a
try{
sum += array[j][col];
}catch(ArrayIndexOutOfBoundsException e){
}
block, where it simply skips over if there is nothing, and keeps going to the next one.
you will have to import that exception as well. If you run into trouble, just look up how try/catch blocks work

Here is another solution I found.
// returns sum of the column 'col' of array
public static int columnSum(int[][] array, int col) {
int sum = 0;
// for loop traverses through array and adds together only items in a specified column
try {
for (int j = 0; j < array.length; j++) {
if (col < array[j].length)
sum += array[j][col];
}
}
catch (ArrayIndexOutOfBoundsException e){
}
return sum;
} // end columnSum()

public class JaggedArrayColSum {
int[] jackedArrayColSum(int arr[][]){
int sum;
int maxLen=0;
boolean status;
//START #MAX LENGTH
//Finding the max length of inner array
for(var a=0;a<arr.length;a++) {
status=true;
for(var b=0;b<arr.length;b++) {
if(a==b)continue;
if(arr[a].length<arr[b].length) {
status=false;
break;
}
if(status)maxLen=arr[a].length;
}
}
//END #MAX LENGTH
//START #SUM JAGGED ARRAY
int [ ] arr1=new int[maxLen];
for(var a=0;a<maxLen;a++) {
sum=0;
for(var b=0;b<arr.length;b++) {
if(arr[b].length>a)sum+=arr[b][a];
}
arr1[a]=sum; //Adding values to the the return array index
}
//END #SUM JAGGED ARRAY
return arr1;
}
public static void main ( String [ ] args ) {
int [][]arr= {{1},{1,3},{1,2,3,4},{1,2,3,4,5,6,7}};
for(int x:new JaggedArrayColSum().jackedArrayColSum ( arr ))System.out.print ( x +" " ) ;
}
}

Related

Given an array in which arr[i] = i-1 with the following method, what will be the output?

I'm given the following method written in pseudo-code
for i=1 to floor(n/2)
if arr[i] != 0 then
for(j=2 to floor(n/i)
arr[i*j] = 0
I need to find the output and to prove that it's indeed the output.
So far I tried to write the code in Java and to try different inputs and array sizes but to no avail.
Putting it here if it's of any help:
public class Checking
{
private static int method(int[] A,int n)
{
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
if(A[i] != 0)
{
for(int j=2;j<=java.lang.Math.floor(n/i);j++)
{
A[i*j]=0;
System.out.println("The index ofA["+i*j+"] became "+A[i*j]);
}
}
//System.out.print(", "+A[i]);
}
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
return 0;
}
public static void main(String[] args)
{
int[] A = {-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
System.out.println(method(A,20));
}
}
Thank you.
You can change the following:
In your main method remove
System.out.println(method(A,20));
as it will always print 0 as you return 0; from the method().
As you print everything in your method() change the following (as it does not print the full array but from index 1 (missing index 0) to floor n/2)
for (int i=1;i<=java.lang.Math.floor(n/2);i++)
{
System.out.print(", "+A[i]);
}
to
for (int i=0;i<A.length; i++)
{
System.out.print(", "+A[i]);
}
So you can print the whole array.
For simplicity you can use Array's print method to print the array without a for loop
System.out.println(Arrays.toString(A));

Have to create 2d array (4x4) array and has to fill the diagnal with 1s and rest of the spaces with 0s

public class sampleq8
{
public static void main(String args[])
{
int size =4;
int array[][]=new int[size][size];
for(int i=0; i<array.length;i++)
{
for(int j=0;j<array.length;j++)
{
array[0][0]=1;
}
//array[4][4]=1;
// array[
System.out.println(array[i][i]);
}
}
}
i got to print out the first column correctly i cant produce the rest of the rows or the columns i need some suggestions please thanks.
Java initializes all the values of your array to 0 automatically, you only need to assign values to the diagonal.
int size =4;
int array [][] = new int[size][size];
for (int i =0;i<size;i++){
array[i][i]=1;
}
System.out.println(Arrays.deepToString(array));
This does the job.
In your version you are only setting the value 1 to the element with coordinates 0,0 in your array
To print your array you need to import java.util.Arrays;
This one will print the matrix nicely
for (int i =0 ;i<4;i++){System.out.println(Arrays.toString(array[i]));}
Your assignment is always using the 0,0 element.
array[0][0]=1
You need to set the assignment like this:
array[i][j]=1
try something like this, dont know if it works, i cant run it right now
for(int i = 0; i<size; i++)
{
array[i][i] = 1;
}
for(int i=0; i<array.length;i++)
{
for(int j=0;j<array.length;j++)
{
if(array[i][j] != 1)
array[i][j]=0;
}
}

Transform an array to another array by shifting value to adjacent element

I am given 2 arrays, Input and Output Array. The goal is to transform the input array to output array by performing shifting of 1 value in a given step to its adjacent element. Eg: Input array is [0,0,8,0,0] and Output array is [2,0,4,0,2]. Here 1st step would be [0,1,7,0,0] and 2nd step would be [0,1,6,1,0] and so on.
What can be the algorithm to do this efficiently? I was thinking of performing BFS but then we have to do BFS from each element and this can be exponential. Can anyone suggest solution for this problem?
I think you can do this simply by scanning in each direction tracking the cumulative value (in that direction) in the current array and the desired output array and pushing values along ahead of you as necessary:
scan from the left looking for first cell where
cumulative value > cumulative value in desired output
while that holds move 1 from that cell to the next cell to the right
scan from the right looking for first cell where
cumulative value > cumulative value in desired output
while that holds move 1 from that cell to the next cell to the left
For your example the steps would be:
FWD:
[0,0,8,0,0]
[0,0,7,1,0]
[0,0,6,2,0]
[0,0,6,1,1]
[0,0,6,0,2]
REV:
[0,1,5,0,2]
[0,2,4,0,2]
[1,1,4,0,2]
[2,0,4,0,2]
i think BFS could actually work.
notice that n*O(n+m) = O(n^2+nm) and therefore not exponential.
also you could use: Floyd-Warshall algorithm and Johnson’s algorithm, with a weight of 1 for a "flat" graph, or even connect the vertices in a new way by their actual distance and potentially save some iterations.
hope it helped :)
void transform(int[] in, int[] out, int size)
{
int[] state = in.clone();
report(state);
while (true)
{
int minPressure = 0;
int indexOfMinPressure = 0;
int maxPressure = 0;
int indexOfMaxPressure = 0;
int pressureSum = 0;
for (int index = 0; index < size - 1; ++index)
{
int lhsDiff = state[index] - out[index];
int rhsDiff = state[index + 1] - out[index + 1];
int pressure = lhsDiff - rhsDiff;
if (pressure < minPressure)
{
minPressure = pressure;
indexOfMinPressure = index;
}
if (pressure > maxPressure)
{
maxPressure = pressure;
indexOfMaxPressure = index;
}
pressureSum += pressure;
}
if (minPressure == 0 && maxPressure == 0)
{
break;
}
boolean shiftLeft;
if (Math.abs(minPressure) > Math.abs(maxPressure))
{
shiftLeft = true;
}
else if (Math.abs(minPressure) < Math.abs(maxPressure))
{
shiftLeft = false;
}
else
{
shiftLeft = (pressureSum < 0);
}
if (shiftLeft)
{
++state[indexOfMinPressure];
--state[indexOfMinPressure + 1];
}
else
{
--state[indexOfMaxPressure];
++state[indexOfMaxPressure + 1];
}
report(state);
}
}
A simple greedy algorithm will work and do the job in minimum number of steps. The function returns the total numbers of steps required for the task.
int shift(std::vector<int>& a,std::vector<int>& b){
int n = a.size();
int sum1=0,sum2=0;
for (int i = 0; i < n; ++i){
sum1+=a[i];
sum2+=b[i];
}
if (sum1!=sum2)
{
return -1;
}
int operations=0;
int j=0;
for (int i = 0; i < n;)
{
if (a[i]<b[i])
{
while(j<n and a[j]==0){
j++;
}
if(a[j]<b[i]-a[i]){
operations+=(j-i)*a[j];
a[i]+=a[j];
a[j]=0;
}else{
operations+=(j-i)*(b[i]-a[i]);
a[j]-=(b[i]-a[i]);
a[i]=b[i];
}
}else if (a[i]>b[i])
{
a[i+1]+=(a[i]-b[i]);
operations+=(a[i]-b[i]);
a[i]=b[i];
}else{
i++;
}
}
return operations;
}
Here -1 is a special value meaning that given array cannot be converted to desired one.
Time Complexity: O(n).

Passing a 2d array and using recursion error

I am doing an assignment and have trouble getting the code compiled. The code must have recursion. The idea is to pass a 2d array sequentially - row by row, column by column and to get a private helper method to match cases and return the result.
I have tried looking at different solutions and everything seems in order, however I get an error:
required: int
found: int[][]
I am passing an array, int row and int column to a method that should be accepting exactly those three.
Take a look:
public static int [][] calculateProximity ( boolean [][] mineField )
{
int [][] proximityField = new int [mineField.length][mineField[0].length];
for (int row = 0; row < mineField.length; row++) {
for (int column=0; column <mineField[row].length; column++) {
proximityField [row][column] = calculateProximity (mineField, row, column);
}
}
return proximityField;
}
private static int [][] calculateProximity (boolean [][] mineField,
int row, int column)
{
int [][] proximityField;
if (row >= mineField.length || column >= mineField[row].length){
return proximityField=0;
}
else if (mineField [row][column]= true){
proximityField[row][column]=1;
return proximityField;
}
else
{
proximityField[row][column]=0;
}
return proximityField;
}
By the way, calculateProximity main method is to return an int 2d array, but it is given a boolean 2d array.
return proximityField=0;, is incorrect. Here, you are returning the result of proximityfield=0. This is going to be a single integer, the value 0. When you assign a variable, the return value is the value you assigned to the variable. You should probably return null instead.
Never use loops while performing recursion. I hope this code gives you some idea:
#include<stdio.h>
#include<stdlib.h>
int i=0,j=0,k=0,flag=0;
int function_Matrix(int arr[][4],int i,int j)
{
if(j==4||i==3)
return 1;
if(flag==0)
{
printf("\t%d",arr[i][j]);
}
function_Matrix(arr,i,j+=1);
printf("\n");
function_Matrix(arr,i+=1,j=0);
flag=1;
}
int main()
{
int x;
int arr[][4]={{1,2,3,4},
{5,6,7,8},
{9,7,6,5}};
function_Matrix(arr,0,0);
}

Sudoku in Java. Index out of Bounds Exception

I've got an IndexOutOfBounds exception in the following program. It consists of three files:
Important are only two of them, the GUI is working fine. Here is the first one:
interface SudokuObserver {
public void modified(int i, int j);
}
public class SudokuData
{
public int[][] feld = new int[9][9];
public SudokuObserver obs = null;
public SudokuData()
{
int i,j;
for (i=0; i<9; i++) {
for (j=0; j<9; j++) {
feld[i][j] = 0;
}
}
}
public int getNumber(int x, int y)
{
return feld[x][y];
}
public void setNumber(int x, int y, int v)
{
feld[x][y] = v;
if (obs != null)
obs.modified(x, y);
}
public void setObserver(SudokuObserver o)
{
obs = o;
}
So the Sudoku field is allocated as a 9x9 integer array. The following file is called SudokuSolver and has an algorithm to write the possible numbers for each square into an ArrayList. Then the second algorithm works as following: He finds the square which has the minimum of possible numbers, sets the first of the numbers saved in the ArrayList on that square and does this recursive, so he starts again at defining the possible numbers for each square, taking the one with the smallest number of possibilities and picks the first one to put it into that field. A for-loop runs over the possible Numbers for each square while doing that.
import java.util.*;
public class SudokuSolver
{
SudokuData data;
public SudokuSolver(SudokuData d)
{
data = d;
}
{
/*Pseudoalgorithm:
- Inserts the numbers 1-9 into a Collection called res
- Looks at line x, which numbers are in there and erases them out of the
collection
- Looks at column y, which numbers are in there and erases them out of the
collection
- Looks in the 3x3 Square (x,y) which numbers are already in there and erases
them out of the collection
- Gives back the possible candidates for that field
*/
Here i initialize my ArrayList.
public ArrayList<Integer> offen(int x, int y)
{
ArrayList<Integer> res = new ArrayList<Integer>();
/* The collection is saved in an ArrayList */
int k = 0;
Here I just fill in the numbers 1-9 in my ArrayList.
for (int i=1;i<10;i++)
{
res.add(i);
}
Now comes the difficult part: I loop over j from zero to nine, then over k. The line is constant with the given x, the j runs over the columns, so i got every square in the given line, and in every square i check for every number from 1-9. Care: the index goes from 0-9 while the elements go from 1-9 so k has to be 0-9 cause the get()-method takes an index as input. If there is any compliance I remove the element from the ArrayList.
for (int j=0;j<9;j++)
{
for (k=0;k<9;k++)
{
if (this.data.feld[x][j] == (res.get(k)))
res.remove(k);
}
Same stuff as above for the columns, constant column and j loops.
for (k=0;k<9;k++)
{
if (this.data.feld[j][y] == res.get(k))
res.remove(k);
}
}
Now i get my inputs in two new variables, just because i had typed the code part below before with wrong variable names.
int m = x;
int n = y;
Here is the part for the 3x3 squares, i do this with if conditions, so this is just one of the 9 parts, I didn't want to post them all here, cause they just differ in a few constants. I check in which square my input x,y is, and then I loop over the square and check which numbers are there, which are also still in my ArrayList and remove them.
if (m<=2 && n<=2)
{
for (m=0;m<3;m++)
{
for (n=0;n<3;n++)
{
for (k=0;k<9;k++)
{
if (this.data.feld[m][n] == res.get(k))
res.remove(k);
}
}
}
}
Now I return the ArrayList
return res;
}
//findSolution() finds a Solution
public boolean findSolution()
{
/*Possible Strategy:
- Find the square, which has the fewest possible candidates
- If there are more than one candidates, who have the minimum of candidates,
take any of them
- If there are no more open candidates, there is a solution found. Return
true
- Loop over the candidates of this square and by setting the first possible
candidate into this square[x][y]
- Call the method findSolution() recursive to find in dependence of the set
value the values for the other fields
If there is a blind alley, take the next possible candidate (Backtracking!)
*/
int j = 0;
int k = 0;
int x = 0; // x coordinate of the field with the fewest open candidates
int y = 0; // y coordinate of the field with the fewest open candidates
int counter_offene_felder = 0; // counts the number of open fields
int min = 9;
I'm looping over j and k, looking if the number of possible candidates is more than 0, that means I'm running through the whole sudoku field and count the number of open fields.
for (j=0;j<9;j++)
{
for (k=0;k<9;k++)
{
if ( this.offen(j,k).size() >= 0)
{
counter_offene_felder += 1;
}
If the number is < than min = 9 possible candidates, i take it as the min and save the coordinates of that field
if ( (this.offen(j,k)).size() < min )
{
x = j;
y = k;
}
}
}
now i initialize and ArrayList for the field with the fewest possible candidates and put them into this ArrayList with my offen-method
ArrayList<Integer> candidate_list = this.offen(x,y);
for (k=0;k<this.offen(x,y).size();k++)
{ // runs over candidates
int v = this.offen(x,y).get(k); // takes the first candidate
this.data.setNumber(x,y,v); // writes the first candidate into square [x][y]
this.findSolution(); // calls findSolution() recursive
}
If there are no more open fields, I've found a solution
if (counter_offene_felder == 0)
{
return true;
}
else return false;
}
}
The problem is, that I get an IndexOutOfBounds Exception at line 39, at Index 8 Size 8. But I don't know why. :(
Not positive that this is where you are getting your error... but you could run into an issue when you do something like this.
for (k=0;k<9;k++)
{
if (this.data.feld[j][y] == res.get(k))
res.remove(k);
}
For instance, say that at k=1 the if statement evaluates to true. Then you will remove an element from the ArrayList. Then when k=8, and IndexOutOfBounds exception will be thrown because the ArrayList only contains 8 elements (0-7)
Assuming that no other threads will be modifying this.data.feld[][], you will only ever get one match when going through this loop.. so you could do something like this...
int match = -1;
for (k=0;k<res.size();k++) {
if (this.data.feld[j][y] == res.get(k)){
match = k;
break;
}
}
if(match != -1)
res.remove(match);
I think the contains() method will help eliminate your exceptions for this loop.
Try replacing your code with this:
for (m=0;m<3;m++)
{
for (n=0;n<3;n++)
{
if (res.contains(this.data.field[m][n]))
res.remove(res.indexOf(this.data.field[m][n]));
}
}
It will iterate over the data.field, and check the ArrayList to see if it contains the value at m,n. If it does, it will remove it.

Resources