I want to write an algorithm that pretty much does this with a sorted array full of integers:
1) {8,9,10,14,15,16,19,20,21} -> {8,10,14,16,19,21}
2) {8,9,10,11,12,14,15,16,18,19,20,21} -> {8,12,14,16,18,21}
I've come up with this algorithm:
int l=x.length;
for(int k=0;k<l-1;k++)
{
if (x[k]+1==x[k+1] && x[k]+2==x[k+2])
{
for(int z=k+1;z<l;z++)
{
if(z+1==l)
x[z]=0;
else
x[z]=x[z+1];
}
l--;
}
}
This algorithm works well with the above mentioned first example but if I instead put more than 3 consecutive numbers it screws up the result, for example:
{8,9,10,11,12,14,15,16,18,19,20,21} -> {8,10,12,14,16,18,20,21} instead of {8,12,14,16,18,21}
What am I doing wrong? And how can I change my algorithm to successfully eliminate all intermediary consecutive numbers
@Tunaki is right.
I'd do something along the lines of this:
public static int[] filterImmediary(int[] x) {
/*
* Construct a boolean array that will be used to indicate whether the
* corresponding element in the int array is an immediary consecutive
* number.
*/
int l = x.length;
boolean[] rem = new boolean[l];
int numKeeps = 0;
/*
* Fill boolean array
*/
for (int k = 0; k < l - 1; k++) {
int f = 1;
while (k + f < l && x[k] + f == x[k + f]) {
if (k + f + 1 < l && x[k] + f + 1 == x[k + f + 1]) {
rem[k + f] = true;
}
f++;
}
if (!rem[k]) {
numKeeps++;
}
}
/*
* Construct a new array with no immediary consecutive numbers to return
* instead of mutating the original array.
*/
int[] newX = new int[numKeeps+1];
int i = 0;
for (int k = 0; k < l; k++) {
if (!rem[k]) {
newX[i] = x[k];
i++;
}
}
return newX;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments