assassinweed2 - 9 months ago 38

Java Question

I am currently creating a program where the user inputs an array of integers. The program has to find the longest increasing sequence of consecutive elements. So if the user enters "3,2,1,2,4,6,7,8,1,2" the program will output "1,2,4,5,6,7,8". However, I keep running into 2 errors.

The first error is that when xs = 1000,97777,487,8274,972837. The program will output "1000,97777" instead of "487,8274,972837". Logically this is wrong since the first output is not the "LONGEST" increasing sequence of consecutive element.

The second error is that when xs = 2,7. It seems to output an empty array instead of "2,7". I'm assuming it's because there aren't enough elements perhaps?

`static int[] increasing(int[] xs){`

ArrayList<Integer> current_array = new ArrayList<Integer>();

ArrayList<Integer> list = new ArrayList<Integer>();

int c_counter = 0;

for (int i = 0; i<(xs.length); i++){

if (i==0){

if (xs[i+1] > xs[i]){

current_array.add(xs[i]);

c_counter++; //keeps track of how many elements have been added

}

}

else if ((xs[i] > xs[i-1])){

if (c_counter==0){

current_array.add(xs[i-1]); //makes sure the smaller number gets added too

current_array.add(xs[i]);

c_counter = c_counter + 2;

} else{

current_array.add(xs[i]);

c_counter++;

}

} else {

if (current_array.size()>list.size()){ //compares sizes to find the longest sequence

list.clear();

for (int k=0; k<(current_array.size()); k++){

if (current_array.get(k) != 0){ //removes any null values

list.add(current_array.get(k));

}

}

current_array.clear(); //clears it to restart and find any longer sequences

c_counter = 0;

}

}

}

int[] out_array = list.stream().mapToInt(i->i).toArray(); //converts from arraylist to int[] as that's the format it must output

out_array = list.stream().filter(i->i != null).mapToInt(i->i).toArray();

return out_array;

}

Answer Source

It takes too long time to understand your code. Try this out:

```
List<Integer> test = new ArrayList<Integer>();
test.add(3);
test.add(2);
test.add(1);
test.add(2);
// test.add(4);
// test.add(6);
// test.add(7);
// test.add(8);
test.add(1);
test.add(2);
test.add(1000);
test.add(97777);
test.add(487);
test.add(8274);
test.add(972837);
List<Integer> output = new ArrayList<Integer>();
List<Integer> temp = new ArrayList<Integer>();
for(int i = 0; i < test.size(); i++) {
int current = test.get(i);
int next = Integer.MIN_VALUE;
if(i + 1 < test.size()) next = test.get(i + 1);
if(current > next) {
if(output.size() <= temp.size()) {
temp.add(current);
output = new ArrayList<Integer>(temp);
}
temp.clear();
} else {
temp.add(current);
}
}
output.forEach(i -> System.out.print(i + ", "));
```

If you want the longest decreasing output, change `int next = Integer.MAX_VALUE;`

and `if(current > next)`

to `if(current < next)`