Getting sub-array from a 2D double[][] array [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I'm trying to get a sub-array from double[][] 3x3 matrices (to calculate a determinant). I keep getting the ArrayIndexOutOfBoundsException.
Any idea why ?
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex, int columnEndIndex) {
double[][] subArray = new double[rowEndIndex-rowStartIndex+1][columnEndIndex-columnStartIndex+1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}

Looks like it has something to do with array initialization, the array passed to the method does not seem to be 3x3. E.g, following does not produce an Exception:
public static void main(String[] args) throws IOException {
double[][] array = new double[][]{{1d,1d,1d},{2d,2d,2d},{3d,3d,3d}};
double[][] subArray = get2DSubArray(array, 1, 2, 1, 2);
for(double[] arrayElement : subArray){
for(double number : arrayElement){
System.out.println(number);
}
}
}
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row < rowEndIndex; row++) {
subArray[row] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex);
}
return subArray;
}
Update
Although the above solution does not produce an Exception, it does not produce correct output as well. Mainly because of the following reasons:
Third argument for Arrays.copyOfRange method is exclusive, so we have to pass columnEndIndex+1 for it to work
for loop only executes once for provided set of arguments whereas it should execute at least twice
Instead of assigning Arrays.copyOfRange to subArray[row], we need to assign it to subArray[<zero based index>]
Below solution does work:
public double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
int index = 0;
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[index++] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}

If the row start was 500 and the end was 505, the variable in the for loop would start at 500 instead of 0. You want to replace "subArray[row] =" with "subArray[row-rowStartIndex] =". You are referencing where it would of been in the larger array compared to where the copy will be in the smaller array.
Edit:
//Fixed Version:
public static double[][] get2DSubArray(double[][] largeArray, int rowStartIndex, int rowEndIndex, int columnStartIndex,
int columnEndIndex) {
double[][] subArray = new double[rowEndIndex - rowStartIndex + 1][columnEndIndex - columnStartIndex + 1];
for (int row = rowStartIndex; row <= rowEndIndex; row++) {
subArray[row-rowStartIndex] = Arrays.copyOfRange(largeArray[row], columnStartIndex, columnEndIndex+1);
}
return subArray;
}

Related

Return a zigzag array

I have two questions:
public static int[] everyOther(int[] arr)
Given an integer array arr, create and return a new array that contains precisely the elements in the even-numbered positions in the array arr. Make sure that your method works correctly for arrays of both odd and even lengths, and for arrays that contain zero or only one element. The length of the result array that you return must be exactly right so that there are no extra zeros at the end of the array.
public static int[][] createZigZag(int rows, int cols, int start)
This method creates and returns a new two-dimensional integer array, which in Java is really just a one-dimensional array whose elements are one-dimensional arrays of type int[]. The returned array must have the correct number of rows that each have exactly cols columns. This array must contain the numbers start, start + 1, ..., start + (rows * cols - 1) in its rows in order, except that the elements in each odd-numbered row must be listed in descending order.
For example, when called with rows = 4, cols = 5 and start = 4, this method should create and return the two-dimensional array whose contents are
4 5 6 7 8
13 12 11 10 9
14 15 16 17 18
23 22 21 20 19
when displayed in the traditional matrix form that is more readable for the human than the more realistic form of a one-dimensional array whose elements are one-dimensional arrays of rows.
public static int[] everyOther(int[] arr){
for (int i = 0 ; i < aList.size() ; i+=2)
{
return( aList.get(i) + " ") ;
}
}
public static int[][] createZigZag(int rows, int cols, int start){
{
int evenRow = 0;
int oddRow = 1;
while (evenRow < rows)
{
for (int i = 0; i < cols; i++)
{
return(start[evenRow][i] + " ");
}
evenRow = evenRow + 2;
if(oddRow < rows)
{
for (int i = cols - 1; i >= 0; i--)
{
return(start[oddRow][i] + " ");
}
}
oddRow = oddRow + 2;
}
}
}
does this make sense?
Try this as an attempted solution to your exercise.
Notes:
If you copy paste this whole code, make sure your class file is named TestExample as is this one.
Inside main method are just some tests so that you see the output printed and you can verify it. You can ignore Arrays.toString(), it's just to print the int[] arrays to the screen in a better format.
Wherever you see final, you can ignore it or erase it (for now, that you still learn the language). In a simple first look, it means you don't intend to change this variable. After you proceed in learning the language, visit this again but this time consider that it "locks" the variable name to a specific reference inside the enclosing scope. It doesn't guarantee immutability of the value however except if it is a primitive value (int, long, float, double etc).
Notice that the arrays have to have been initialized (their dimensions) before you assign any value to a specific position of the array.
For the everyOther method, note that Java is zero-based in its indexing and thus in the array new int[] { 8, 9, 10, 11 }; your first odd-indexed value is 9 and the second is 11.
General advice: If you are now starting with a language, use an IDE like Eclipse (it's free & open source), IntelliJ (free) or NetBeans(free & open source). It would red-underline the errors in your code and (if configured) display warning messages as well for dangerous practices.
Code:
import java.util.Arrays;
public class TestExample
{
public static int[][] createZigZag(final int rows, final int cols, int start)
{
final int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = start;
start++;
}
}
return array;
}
public static int[] everyOther(final int[] array)
{
int otherArrayLength;
if (array.length % 2 == 0)
{
otherArrayLength = array.length / 2;
}
else
{
otherArrayLength = array.length / 2 + 1;
}
final int[] otherArray = new int[otherArrayLength];
int count = 0;
for (int i = 0; i < array.length; i += 2)
{
otherArray[count] = i;
count++;
}
return otherArray;
}
public static void main(final String[] args)
{
final int[] testArray = new int[] { 0, 1, 2, 3, 4, 5, 6 };
final int[] everyOtherArray = everyOther(testArray);
System.out.println(Arrays.toString(everyOtherArray));
final int rows = 4;
final int cols = 5;
final int start = 4;
final int[][] zigzagArray = createZigZag(rows, cols, start);
for (int i = 0; i < rows; i++)
{
System.out.println(Arrays.toString(zigzagArray[i]));
}
}
}

How to write a method that return the sum of a given column in a array? JAVA [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I should create a method that print the sum of a given column in the main. This program shows a compilation error of:
Error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at algproo2.ALGPROO2.sumColumn(ALGPROO2.java:29)
at algproo2.ALGPROO2.main(ALGPROO2.java:24)
Java Result: 1
What should i do?
public class ALGPROO2
{
public static void main(String[] args)
{
int[][] a = {
{-5,-2,-3,7},
{1,-5,-2,2},
{1,-2,3,-4}
};
System.out.println(sumColumn(a,1)); //should print -9
System.out.println(sumColumn(a,3)); //should print 5
}
public static int sumColumn(int[][] array, int column)
{
int sumn = 0;
int coluna [] = array[column];
for (int value : coluna )
{
sumn += value;
}
return sumn;
}
}
When you do int coluna [] = array[column]; you're actually getting one row, not the column. For example:
Doing array[1] would give you this array:
{1,-5,-2,2}
Thus, doing array[3] will give you an error as there is no 4th row / 4th array (as arrays start at 0). Instead, you need to loop over your rows (ie the number of rows is array.length). Then at each row, you can access the value at that particular column:
public static int sumColumn(int[][] array, int column) {
int sumn = 0;
for(int i = 0; i < array.length; i++) {
int row[] = array[i]; // get the row
int numFromCol = row[column]; // get the value at the column from the given row
sumn += numFromCol; // add the value to the total sum
}
return sumn; // return the sum
}

How to use create 2 Array with User input with Std.readAllInts()

This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.

Removing specific value from array (java)

i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}

2D array help - multiplying a negative number

The error message is - Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
I am passing a 2d array into a method and the multiplying the values inside the array by 2. here is the method below.
it works correctly when I pass in the first array from main but not the second - these are also shown below the method code
does anyone have an idea how to amend this error? I also cannot hard code the loop iterations etc
int setuparray2 [][] = new int [][] {{4, 5},{6, 9} };
int setuparray3 [][] = new int [][] {{4, 6, 3},{-1,9,-5}};
scalarMultiplication(2,setuparray1);
scalarMultiplication(2,setuparray3);
public static void scalarMultiplication( int factor, int[][] a)
{
//creates a new array to hold the multiplied value
int multiplyArray [][] = new int [a.length][a.length];
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < a[i].length; j++)
{
//multiplys each element in the array by the factor
multiplyArray[i][j] = a[i][j] * factor;
}
}
//prints the array with the results
printArray(multiplyArray);
}
when creating multiplyArray you do not reserve enough space.
Instead of:
int multiplyArray [][] = new int [a.length][a.length];
Write:
int multiplyArray [][] = new int [a.length][a[0].length];
You are initializing it in wrong way, below should be the correct way
int multiplyArray [][] = new int [2][3];

Categories