首页 > 解决方案 > 数组扩展/缩减

问题描述

我使用 Oracle JGeometry 方法,该方法返回(或作为方法参数)二维段作为双数组(x1,y1,x2,y2 ... xn,yn)。我想扩展这个数组以包含 3D 段作为双数组 (x1,y1,z1,x2,y2,z2 ... xn,yn,zn) 默认 Z 值或减少到 2D (通过删除所有 Z 坐标)。我编写了简单的实用方法来制作它。有没有更简单或更聪明的方法来做到这一点?

从 2D 到 3D 的转换:

public static double[] to3D(double z, double[] inputArray) {
    List<Double> convertedItems = new ArrayList<>();
    for (int i = 0; i < inputArray.length; i++) {
        convertedItems.add(inputArray[i]);
        if ((i + 1) % 2 == 0) {
            convertedItems.add(z);
        }
    }
    return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}

从 3D 到 2D 的转换:

public static double[] to2D(double[] inputArray) {
    List<Double> convertedItems = new ArrayList<>();
    for (int i = 0; i < inputArray.length; i++) {
       if ((i + 1) % 3 == 0) {
           continue;
       }
       convertedItems.add(inputArray[i]);     
    }
    return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}

标签: javaarraysalgorithm

解决方案


这应该会提供一些性能改进。

public static double[] to3D(double z, double[] inputArray) {
    if (inputArray.length % 2 != 0) throw new IllegalArgumentException();
    double[] convertedArray = new double[inputArray.length / 2 * 3];
    for (int i = 0; i < inputArray.length / 2; i++) {
        System.arraycopy(inputArray, i * 2, convertedArray, i * 3, 2);
        convertedArray[i * 3 + 2] = z;
    }
    return convertedArray;
}

public static double[] to2D(double[] inputArray) {
    if (inputArray.length % 3 != 0) throw new IllegalArgumentException();
    double[] convertedArray = new double[inputArray.length / 3 * 2];
    for (int i = 0; i < inputArray.length / 3; i++) {
        System.arraycopy(inputArray, i * 3, convertedArray, i * 2, 2);
    }
    return convertedArray;
}

推荐阅读