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;
}
}
1条答案
按热度按时间db2dz4w81#
您可以使用moduloMapx索引,并使用简单的除法将二维数组的y索引Map到一维索引。
解决方案首先用0初始化数组,时间和内存复杂度显然是
Θ(xy)
。在Java中实现的相同算法如下所示: