Skip to content

Instantly share code, notes, and snippets.

@gfrison
Created August 1, 2018 08:40
Show Gist options
  • Save gfrison/0343363c5e26afca5514b2ffefee0e4b to your computer and use it in GitHub Desktop.
Save gfrison/0343363c5e26afca5514b2ffefee0e4b to your computer and use it in GitHub Desktop.
I need to find a way to create a new array in Java that will insert intermediate values between the values of an already-existing array.
/**
* > arr = {1, 2, 3}, size = 5
* < [1.0, 1.5, 2.0, 2.5, 3.0]
* @param arr
* @param newSize
* @return
*/
public static double[] growIntermediate(double[] arr, int newSize) {
if (newSize < arr.length) {
throw new IllegalArgumentException("newSize lower than array length");
}
if (newSize == arr.length) {
return arr;
}
int skip = max(1, arr.length / (newSize - arr.length));
int minFills = max(1, (newSize - arr.length) / arr.length);
log.debug("skip:{}, minFills:{}", skip, minFills);
int idx = 0;
int destPos = 0;
double[] ret = new double[newSize];
while (idx < arr.length) {
System.arraycopy(arr, idx, ret, destPos, min(skip, arr.length - idx));
idx += skip;
destPos += skip;
if ((destPos + minFills < newSize) && (idx < arr.length)) {
final double[] intheBetween = intheBetween(arr[idx - 1], arr[idx], minFills);
System.arraycopy(intheBetween, 0, ret, destPos, minFills);
destPos += minFills;
}
}
double[] rett = new double[destPos];
System.arraycopy(ret, 0, rett, 0, destPos);
return rett;
}
/**
* > intheBetween(0, 1, 3)
* < [0.3333333333333333, 0.6666666666666666]
*/
public static double[] intheBetween(double a, double b, int n) {
double step = (b - a) / (n + 1);
return range(0, n).mapToDouble(i -> a + (step * (i + 1))).toArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment