Matrix Layer Rotation

Matrix Layer Rotation - A HackerRank challenge solution

Problem

You are given a 2D matrix of dimension and a positive integer . You have to rotate the matrix times and print the resultant matrix. Rotation should be in anti-clockwise direction.

Rotation of a matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only.

Matrix Rotation

Matrix Rotation

Read more on the challenge page…

My Solution

I’m providing the solution for Python and JS, please leave on the comments if you found a better way.

I really got the solution inspired by the image on the problem statement above. The idea is to resolve one “layer” at a time.

For each layer I’m building a flat array with the elements assigned to the correct position as it’s easier to do this on 1 dimension. After I complete the array, I then proceed to recreate the matrix layer from it.

The problem was actually quite simple to solve, though it looks messy.

I like using variables to define the direction where I’m going while looping through the matrix layer, though some solutions for problems like this usually don’t use this directional variables, but multiple loops instead. anyway works.

Here is my solution as always for Python and JS

Si te gusta el contenido, por favor apoya mi trabajo!

Juan Cruz Martinez - Author @ Live Code Stream

Juan Cruz Martinez

¡Hola!

Soy Juan Cruz Martinez, el fundador de LiveCodeStream.dev. Me encanta programar y creo en el poder de la programación no solo para construir un mundo mejor, sino para hacer que TU vida sea mejor.

Fundé LiveCodeStream.dev porque quería ayudarte a aprender a programar, construir una mejor carrera y, en última instancia, crear una vida mejor. Eso me sucedió hace más de una década cuando comencé a programar, y le sucede a decenas de miles de personas a diario. Quiero que TÚ te unas a esa revolución.

No importa cómo lo llames, escribir código, programación, desarrollo de software o cualquier otra cosa, las habilidades involucradas están en una demanda cada vez mayor. Y ya sea que quieras incursionar en el desarrollo de sitios web, diseño de juegos, desarrollo de blockchain o cualquier otra cosa, quiero ayudarte.