2 D配列複写の回転

2125 ワード

時計回りに回転
console.log(board)
function rotateRigth(arr){
	let n=arr[0].length
	let m=arr.length
	let result=Array.from({length:n},()=>Array.from({length:m},()=>0))
	result.forEach((_,i)=>{
	        _.forEach((v,j)=>{
	            result[i][j]=arr[m-j-1][i]
	        })
	})
    return result
}
console.log(rotateRigth(board))    
board
[
  [ 'C', 'C', 'B', 'D', 'E' ],
  [ 'A', 'A', 'A', 'D', 'E' ],
  [ 'A', 'A', 'A', 'B', 'F' ],
  [ 'C', 'C', 'B', 'B', 'F' ]
]
result
[
  [ 'C', 'A', 'A', 'C' ],
  [ 'C', 'A', 'A', 'C' ],
  [ 'B', 'A', 'A', 'B' ],
  [ 'B', 'B', 'D', 'D' ],
  [ 'F', 'F', 'E', 'E' ]
]
反時計回りに回転
console.log(board)
function rotateLeft(arr){
	let n=arr[0].length
	let m=arr.length
	let result=Array.from({length:n},()=>Array.from({length:m},()=>0))
	result.forEach((_,i)=>{
	        _.forEach((v,j)=>{
	            result[i][j]=arr[j][m-i]
	        })
	})
    return result
}
console.log(rotateLeft(board))      
board
[
  [ 'C', 'C', 'B', 'D', 'E' ],
  [ 'A', 'A', 'A', 'D', 'E' ],
  [ 'A', 'A', 'A', 'B', 'F' ],
  [ 'C', 'C', 'B', 'B', 'F' ]
]
result
[
  [ 'E', 'E', 'F', 'F' ],
  [ 'D', 'D', 'B', 'B' ],
  [ 'B', 'A', 'A', 'B' ],
  [ 'C', 'A', 'A', 'C' ],
  [ 'C', 'A', 'A', 'C' ]
]