【问题标题】:Algorithm to display matrix in relative position of coordinates在坐标的相对位置显示矩阵的算法
【发布时间】:2018-08-31 19:25:36
【问题描述】:

考虑x=0 and y=0作为原点,向下y-axis和向右x-axis作为正轴,是否有任何标准方法或算法用于空间中相对位置的矩阵变换。

[ [{x:36,y:14},{x:242,y:14}],
  [{x:36,y:133}],
  [{x:36,y:252}],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]

现在因为这个数组数组的长度是 5 并且其中最长数组的长度是 4,所以我需要大小为 5 * 4 的变换矩阵 格式如下。

[ [{x:36,y:14},{x:242,y:14},null,null],
  [{x:36,y:133},null,null,null],
  [{x:36,y:252},null,null,null],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [null,{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]

在上述情况下,保留了相对位置。

提前致谢!!

【问题讨论】:

  • 最长的数组是否总是包含所有x 值?或者你能有像[ [{x:1,y:8},{x:2,y:8}], [{x:1,y:9},{x:3,y:9}] ] 这样输出数组长度为3的东西吗?

标签: javascript algorithm multidimensional-array transform coordinate-systems


【解决方案1】:

解决方案首先将所有唯一的 x 值减少到排序的平面数组中。

然后遍历每一行数据,遍历每一行数组将null拼接到孔中

let data =[ [{x:36,y:14},{x:242,y:214}],
  [{x:36,y:133}],
  [{x:36,y:252}],
  [{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],
  [{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]
  
  
let xVals  = [...new Set(data.reduce((a,c)=>a.concat(c.map(({x})=>x)),[]))].sort((a,b)=>a-b)

data.forEach(row=>{
   xVals.forEach((x,i)=>{
      if(row[i] === undefined  || row[i].x > x){
          row.splice(i,0, null)
      }
   });
});

 data.forEach(arr=>console.log(JSON.stringify(arr)))

【讨论】:

    【解决方案2】:

    检查这段代码。解释将在那里评论。

    function normalize(array){
    
    	// Get the largest sub-array. We will save this as a reference
    	// to use it later
    	var longest_value = array.reduce((a,b)=>a>b?a:b)
    
    
    	// map each element in the main array
    	return array.map(function(a){ 
    
    		// for each item return a modified copy of the largest one.
    		// To do this we map it
    		return longest_value.map(function(b,i){
    
    			// we the item with the same x position in the current main array item
    			var v = a.filter(r=>r.x==b.x)
    
    			//if there is, we return it, is not we return null
    			return v.length? v[0] : null
    		})
    	})
    }
    
    
    console.log(normalize([ [{x:36,y:14},{x:242,y:214}],[{x:36,y:133}],[{x:36,y:252}],[{x:36,y:371},{x:242,y:371},{x:446,y:371},{x:651,y:371}],[{x:242,y:490},{x:446,y:490},{x:651,y:490}] ]))

    【讨论】:

    • 这不适用于其他测试用例 Ex [ [{x:36,y:14},{x:242,y:14}], [{x:36,y:133} ], [{x:36,y:252}], [{x:446,y:371},{x:651,y:371}], [{x:242,y:490},{x: 446,y:490},{x:651,y:490}] ] 应该给我 [{"x":36,"y":14},{"x":242,"y":14}, null,null] VM124:1 [{"x":36,"y":133},null,null,null] VM124:1 [{"x":36,"y":252},null,null,空] VM124:1 [空,空,{"x":446,"y":371},{"x":651,"y":371}] VM124:1 [空,{"x":242 ,"y":490},{"x":446,"y":490},{"x":651,"y":490}] .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    相关资源
    最近更新 更多