代码之家  ›  专栏  ›  技术社区  ›  Aman sharma

坐标相对位置矩阵显示算法

  •  0
  • Aman sharma  · 技术社区  · 8 年前

    矩阵在空间中相对位置的下转换有没有标准的方法或算法 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 其中最长数组的长度为 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}] ]
    

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

    提前谢谢!!

    2 回复  |  直到 8 年前
        1
  •  2
  •   charlietfl    8 年前

    解决方案首先将所有唯一的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
  •  1
  •   Luis felipe De jesus Munoz    8 年前

    检查这段代码。解释将在那里发表。

    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}] ]))