javascript 将一维双精度值转换为二维双精度值

3qpi33ja  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(120)

我尝试将一维double[]中的元素Map到二维double[][]中,并将其排列成矩阵。例如,[1, 2, 3, 4]将被转换成一个2 * 2数组,其中[1, 2]位于第一行,[3, 4]位于第二行。由于没有给出值,因此我需要放入变量而不是实际的整数。
我该怎么做呢?
我试过推和切,但它们只对int有效而不是double

db2dz4w8

db2dz4w81#

您可以使用moduloMapx索引,并使用简单的除法将二维数组的y索引Map到一维索引。
解决方案首先用0初始化数组,时间和内存复杂度显然是Θ(xy)

function reshape(oneDimArray, x, y) {
  if(x < 0 || y < 0) throw new RangeError(`x and y must not be negative`)
  const twoDimArray = [...new Array(y)].map(_ => {
    const array = new Array(x);
    array.fill(0, 0, array.length);
    return array;
  });
  for (let i = 0; i < oneDimArray.length; i++) {
    const yIndex = Math.floor(i / x);
    const xIndex = i % x;
    twoDimArray[yIndex][xIndex] = oneDimArray[i];
  }
  return twoDimArray;
}

const sample = [1, 2, 3, 4];
console.log(reshape(sample, 2, 2));
console.log(reshape(sample, 2, 4));
console.log(reshape(sample, 1, 4));
console.log(reshape(sample, 3, 4));
/* StackOverflow snippet: console should overlap rendered HTML area */
.as-console-wrapper { max-height: 100% !important; top: 0; }

在Java中实现的相同算法如下所示:

import java.util.Arrays;

public class Application {

    public static void main(String[] args) {
        var sample = new double[]{ 1d, 2d, 3d, 4d };
        System.out.println(Arrays.deepToString(reshape(sample, 2, 2)));
        System.out.println(Arrays.deepToString(reshape(sample, 2, 4)));
        System.out.println(Arrays.deepToString(reshape(sample, 1, 4)));
        System.out.println(Arrays.deepToString(reshape(sample, 3, 4)));
    }

    public static double[][] reshape(double[] oneDimArray, int x, int y)
    {
        if(x < 0 || y < 0) throw new IllegalArgumentException("x and y must not be negative");
        var twoDimArray = new double[y][x];
        for (var i = 0; i < oneDimArray.length; i++) {
            var yIndex = (int)(i / x);
            var xIndex = i % x;
            twoDimArray[yIndex][xIndex] = oneDimArray[i];
        }
        return twoDimArray;
    }
}

相关问题