assassinweed2 - 1 month ago 8
Java Question

# Java - Program to find longest increasing sequence of consecutive elements (logical errors)

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]){
c_counter++; //keeps track of how many elements have been added
}
}
else if ((xs[i] > xs[i-1])){
if (c_counter==0){
c_counter = c_counter + 2;
} else{
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
}
}
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;
}

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

List<Integer> test = new ArrayList<Integer>();
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()) {