Mark S. Mark S. - 1 month ago 6
Java Question

Removing useless elements of an array

My program is trying to find the longest contiguous sequence of an array, but the output is wrong.

public class longsec {
public int[] longestForward(int[] arr){
int subSeqLength = 1;
int longest = 1;
int indexStart = 0;
int indexEnd = 0;

for (int i = 0; i < arr.length - 1; i++)
{
if (arr[i] == arr[i + 1] - 1)
{
subSeqLength++;
if (subSeqLength > longest)
{
longest = subSeqLength;
indexStart = i + 2 - subSeqLength;
indexEnd = i + 2;
}

}
else
subSeqLength = 1;
}


int T[] = new int[arr.length];
for (int i = indexStart; i < indexEnd; i++)


T[i]= arr[i];


return T;

}}


input

{23,10,22,5,33,8,9,21,50,41,60,80,99, 22,23,24,25,26,27}

output

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 22, 23, 24, 25, 26, 27]

right output

[22, 23, 24, 25, 26, 27]

What have i done wrong? Thank you.

Answer

The reason why that is happening is because you are creating an array with the same size as the array you inputted. As you can see here.

int T[] = new int[arr.length];

However if just change that piece of code you will get an arrayIndexOutOfBoundsException. And it will be thrown here:

for (int i = indexStart; i < indexEnd; i++)

         T[i]= arr[i];

Because indexStart will ussually be greater than the length of the array. So instead of looping from indexStart to indexEnd what you should be doing is looping through the length of the contiguous numbers like this.

int T[] = new int[longest];

for(int i = 0; i < longest; i++)
    T[i] = arr[i + indexStart];

That should give you your desired output. What I am doing is just offsetting the iteration by the indexStart value of your array.

Comments