javascript - 获取具有二维坐标的一维项目,一维数组从二维数组的左下角开始
问题描述
在提供 2D 坐标后,如何获得从 2D 数组左下角开始的 1D 项目?
var width = 3; // the 2D array width
var height = 3; // the 2D array height
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]; // 1D array
console.log(getIndex(0,2));
console.log(getIndex(1,2));
console.log(getIndex(2,2));
console.log(getIndex(0,1));
console.log(getIndex(1,1));
console.log(getIndex(2,1));
console.log(getIndex(0,0));
console.log(getIndex(1,0));
console.log(getIndex(2,0));
//Desired output: 0 1 2 3 4 5 6 7 8
function getIndex(x, y) {
return ... ; // how????????
}
为了说明,这里是上面代码中一维数组的二维数组:
X
0---2
0 6 7 8
Y | 3 4 5
2 0 1 2
*二维数组中的数字代表一维索引中的位置。
解决方案
要提供所需的访问权限(使用反向行顺序),您可以使用以下公式:
indx = (height - 1 - y) * width + x
推荐阅读
- c# - 在两个服务之间转发 DTO 的序列化为 json 不好的做法
- r - R regular expression to parse call option code
- ruby-on-rails - 如何使用 Spree 在不同的 Rails 页面上导入不同的产品
- java - Java 中的自调用函数中的堆栈溢出错误(岛数)
- reactjs - 为什么我的反应路由器没有将我的快速路由传递给服务器?
- r - 将终端中的变量集导出到 R
- visual-studio - Outlook 加载项的静默安装
- azure - 在 Azure Blob 存储中存储项目级 Blob(图像)
- python - 无法弄清楚为什么代码在 Python 3 中工作,但不是 2.7
- bash - Reformat columns/table to key/value lines in Bash