Issue with ArrayIndexOutOfBoundsException - java

Running this code gives me an array out of bounds exception at the line:
int sum = array[k]+array[l]; //sum of l and k
...Should be a simple fix, but I can't figure out what could be causing it, given I'm using array.length to bound the loop. Can anyone help?
P.S. For the record, this code is supposed to search an int array for pairs of ints or single ints that equal to a target int. It works using solely the println's, but I'm trying to put the numbers that add up to the target into vectors.
public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
//creates vectors, adds inner vector to another vector
outer = new Vector<Vector<Integer>>();
inner = new Vector<Integer>();
outer.add(inner);
for (int k = 0; k <= array.length; k++) {
for (int l = 0; l <= array.length; l++) {
int sum = array[k]+array[l]; //sum of l and k
int i = 0;
if (sum == target) {
inner.add(i, array[l]);
inner.add(i, array[k]);
i++;
//prints combination
System.out.println(array[l]+"+"+array[k]+"="+target);
}
if (k == target) {
inner.add(i, array[k]);
i++;
//prints if int equals target
System.out.println(k+"="+target);
}
if (l == target) {
inner.add(i, array[l]);
i++;
//prints if int equals target
System.out.println(l+"="+target);
}
}
}
//return combinations that add up to target in vector form
System.out.println(outer);
return outer;
}

You need to use "<" instead of "<=" in your for loops.
Since the first position in the array is 0, the last position is length-1. What's happening is that when you reach the last iteration, the index is already out of the bounds of the array.
For instance, if you have an array:
array = [0,1,2,3] the last iteration would be array[4], the length of the array, which is out of the bounds.

the <= should be replaced with <

Change your loops to be:
for (int k = 0; k < array.length; k++)
and
for (int l = 0; l < array.length; l++)
Since arrays are 0-based, you want to go 1 less than the length.

Related

Array is not setting values properly

The first 4 values are set properly in the new array. It has to do with something with my variable 'count' which is not being set properly. The goal of the program is to simply grab the even numbers, and put them in a new array.
I have added 4 to count as a test, and that seems to work perfectly but I dont think that is the issue here.
int[] list = {8,5,4,11,12,2,1,3,10,6,7};
int count = 0;
int gr = 0;
for(int n=0; n<list.length; n++)
{
if(list[n] % 2 == 0)
{
count++;
}
}
int[] evn = new int[count];
for(int k = 0; k<=count; k++)
{
if(list[k] % 2 == 0)
evn[gr++] = list[k];
}
return evn;
Currently, the array prints "8,4,12,2,0,0" when it should print "8,4,12,2,10,6"
This happens because count is always less than the size of the array(list.length), so in the second for-loop you are never iterating till the end of the array.
Change your second for-loop to iterate till the end of the array as shown below :
for(int k = 0; k < list.length; k++)
You're only traversing part of list, as stated in the for condition:
for(int k = 0; k<=count; k++)
^--here--^
This is because count has a lower value than the length of the original array. Change this condition to traverse the whole array:
for(int k = 0; k<list.length; k++)
To traverse the whole list change the following:
for(int k = 0; k<=count; k++)
To
for(int k = 0; k<list.length; k++)

How to convert ArrayList to Array 2 dimension in java

I want to convert ArrayList to Array 2-Dimension
I have the code below:
ArrayList<String> arrayList=new ArrayList();
arrayList.add("A")
arrayList.add("B")
arrayList.add("C")
arrayList.add("D")
arrayList.add("E")
arrayList.add("F")
int nSize=0,n3item=0, remain=0;
nSize=arrayList.size();
n3item=nSize/3;
remain=nSize%3;
String[][] array[n3item][3]
I want to convert ArrayList to array for example
array[0][1]="A"
array[0][2]="B"
array[0][3]="C"
array[1][1]="D"
array[1][2]="E"
array[1][3]="F"
Now I haven't a solution to do this.
In case of remain is not 0. How to give a solution to this problem
I need your help.
Thanks.
You can use a simple nested for-loop to achieve this.
int numCol = 3;
int numRow = (int) Math.ceil(arrayList.size() / ((double) numCol));
String[][] array = new String[numRow][numCol];
int i, j;
for (i = 0; i < numRow; i++) {
for (j = 0; j < 3 && (i * numCol + j) < arrayList.size(); j++) {
array[i][j] = arrayList.get((i * numCol) + j);
}
}
numRow is found by taking the ceil of number of elements in the list divided by num of desired columns.
eg - when arraylist has 7 elements, numRow will be ceil(7/3.0) = 3.
The main trick here is in the inner for-loop condition (i * numCol + j) < arrayList.size(). It enables us to terminate the loop for the condition remain != 0 you mentioned.
Try to think, how you can fill the 2D array with arraylist values. You need to use a nested loop for assigning the values into the 2D array. Outer loop will iterate over the rows and inner loop will fill the values into each 1D array.
int index = 0;
for(int i = 0; i < n3item; i++) {
for(int j = 0; j < 3; j++) {
array[i][j] = arrayList.get(index);
index++;
}
}

Java: Get two arrays and if length of one is smaller than the length of the other, replace missing values with 1

Hi so the question is: if array1 is smaller than array2 replace the missing values with number 1, so that array1 missing values can be multiplied by array2 as if they were the number 1?
Here is my idea of how one could go about it... help with the correct syntax? Best way to go about it?
public addMissingNumber(int[] array1, int[] array2){
for (int 1 = array1.length; i > 0; i--)
for(int j = array2.length; j > 0; j--){
if(array1[i] < array2[j]) {
array1[i].[j] = 1;
/*what I want to say here is that the empty position of the array1[i] that is equivalent to the position of array2[j] that contains a number should become the number 1. How can this be done?*
}
}
}
Here is the original exam question, the second part is what I'm having trouble with:
Write a method called add that takes two arrays v, w of type double as its parameters. The method should return a new array of double formed by adding the corresponding elements of the input arrays. That is to say, element i of the output array should be equal to v[i]+w[i].
If the lengths of v and w are different, the output array should have as length the maximum of (v.length, w.length).
The missing elements of the shorter array should be assumed to be one in the calculation of the output.
Try this:
public double[] addMissingNumber(double[] array1, double[] array2){
double[] arraynew = new double[max(array1.length,array2.length)];
int i = 0;
int j = 0;
int k = 0;
while ( i < array1.length && j < array2.length) {
arraynew[k] = array1[i] + array2[j];
i++;
j++;
k++
}
while(i < array1.length) {
arraynew[k] = array1[i]+1;
i++;
k++;
}
while(j < array2.length){
arraynew[k] = array2[j]+1;
j++;
k++;
}
return arraynew;
}
You don't need to put 1 into the array. Just traverse through both the arrays till they are equal and store the sum . After that the longer array is traversed and 1 is added to it everytime.

Comparing two arrays. Wrong return value (1)

I made this method that compares the numbers of two arrays and then returns how many numbers are equal to each other, but no matter how many numbers are equal, the method returns the value 1 every time.
(both arrays are the same length).
public static void main(String[] args) {
int a [] = {1, 4, 6, 7, 8, 10, 13};
int b [] = {1, 2, 3, 4, 5, 6, 7};
equal(a,b);
}
public static int equal(int[] a, int[] b){
int j = 0;
for(int i = 0; i< a.length-1;i++){
if(a[i] == b[i]){
j++;
}
}
System.out.println(j);
return j;
}
Your code is finding the number that are equal at the same index.
There are several ways you can find the size of the intersection.
A simple but O(m*n) implementation would be to iterate over all elements of b for each element of a.
If the arrays are sorted, you could use separate indexes for the two arrays, advancing each when it can no longer match. This would be O(m+n). (If they're not sorted, you could sort them first, for a cost of O(m log m + n log n ).
If each array has no duplicate members, another way is to compute the size of the intersection is from the size of the set difference. An example of this is at http://ideone.com/6vLAfn. The key part is to convert each array to a set, and determine how many members are in common by removing one set from another.
int aSizeBefore = setA.size();
setA.removeAll( setB );
int aSizeAfter = setA.size();
return aSizeBefore - aSizeAfter;
You should use a nested for loop if you want to check if any single number in array a is also in array b.
e.g.
int numMatches = 0;
for (int i = 0; i < a.length; ++i)
{
for (int j = 0; j < b.length; ++j)
{
if (a[i] == b[j])
++numMatches; //Naive, as obviously if the same number appears twice in a it'll get counted twice each time it appears in b.
}
}
The current code just checks the elements at the same index match i.e
1 == 1 // Yes, increment j
4 == 2 // Nope
6 == 3 // Nope
7 == 4 // Nope
8 == 5 // Nope
10 == 6 // Nope
13 == 7 // Nope
Elements with same values might be in different indexes. You can write as following, assuming the arrays are sorted:
public static int equal(int[] a, int[] b) {
int count = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = 0; i < b.length - 1; j++) {
if (a[j] < b[j]) {
// we came to the part where all elements in b are bigger
// than our selected element in a
break;
}
else if (a[j] == b[j]) {
count++;
}
}
}
System.out.println(count);
return count;
}
If you can't guarantee that the arrays are sorted, you can remove the if-block and remove the else-if's else from the loop.
If you want to know how many numbers are present in both arrays and there is a guarantee that they are ordered, you should try the following:
public static int equal(int[] a, int[] b) {
int j, result = 0;
int lastFound = 0;
for (int i = 0; i < a.length - 1; i++) {
for (j = lastFound; j < b.length; j++) {
if (a[i] == b[j]) {
result++;
lastFound = j;
break;
} else {
if (a[i] < b[j]) break;
}
}
}
return result;
}
Using the variable lastFound will speed your loops, but it is only helpful if the arrays are ordered, as your example indicates.

Array in the reverse order [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}

Categories

Resources