Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
820 views
in Technique[技术] by (71.8m points)

math - How to rotate a matrix in an array in javascript

(disclosure, I'm mostly math illiterate).

I have an array in this format:

var grid = [
  [0,0], [0,1], [0,2], [0,3],
  [1,0], [1,1], [1,2], [1,3],
  [2,0], [2,1], [2,2], [2,3],
  [3,0], [3,1], [3,2], [3,3]
];

I need to "rotate" it by 90deg increments, so it's like this:

var grid = [
  [3,0], [2,0], [1,0], [0,0], 
  [3,1], [2,1], [1,1], [0,1], 
  [3,2], [2,2], [1,2], [0,2], 
  [3,3], [2,3], [1,3], [0,3] 
];

How do I accomplish this in Javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Rotating a two dimensional m x n matrix

Those looking for Rotating a two dimensional matrix (a more general case) here is how to do it.

example: Original Matrix:

[
  [1,2,3],
  [4,5,6], 
  [7,8,9]
]

Rotated at 90 degrees:

[
    [7,4,1]
    [8,5,2]
    [9,6,3]
]

This is done in following way:

matrix[0].map((val, index) => matrix.map(row => row[index]).reverse())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...