【问题标题】:Array extension/reduction数组扩展/缩减
【发布时间】:2021-03-08 09:08:35
【问题描述】:

我使用 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();
}

【问题讨论】:

标签: java arrays algorithm


【解决方案1】:

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

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;
}

【讨论】:

  • 性能真的更好!十个元素从 49 毫秒到 4 毫秒...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
  • 2020-01-21
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 2012-02-17
  • 2014-03-21
相关资源
最近更新 更多