怎么样对二维数组进行拉伸/缩放?
就是以下这道题目,只不过不是根据倍数缩放,而是自定义新数组的宽高
假设有二维数组arr,宽等于2,高等于2。
1.数组左上角区域值是2,右下角区域值是1,拉伸后的数组也要大概保持这个比例.
2.原数组只有0,1,2这3个值,新数组也只能有这3个值
let arr = [
[2, 0],
[0, 1]
];
拉伸成宽等于4,高等于4,的数组就是:
[
[2,2,0,0],
[2,2,0,0],
[0,0,1,1],
[0,0,1,1]
];
拉伸成宽等于4,高等于3,的数组就是:
[
[2,2,0,0],
[2,2,0,0],
[0,0,1,1],
];
或
[
[2,2,0,0],
[0,0,1,1],
[0,0,1,1],
];
function scale(list, newW, newH) {
return Array.from({length: newH}, (_, y) => {
return Array.from({length: newW}, (_, x) =>
list[y / newH * list.length | 0][x / newW * list[0].length | 0]
)
})
}
function scaleList(list, scaleX, scaleY) {
let height = list.length
let width = list[0].length
let nheight = height * scaleY | 0
let nwidth = width * scaleX | 0
let res = new Array(nheight)
for(let h = 0; h < nheight; h++){
let y = h / scaleY | 0
if(nheight % scaleY === 0){
let arr = new Array(nwidth)
for(let w = 0; w < nwidth; w++){
let x = w / scaleX | 0
arr[w] = list[y][x]
}
res[h] = arr
}else{
res[h] = [...res[y]]
}
}
return res
}