# Why does this in-place matrix rotation duplicate values instead of rotating layers correctly?

**URL:** <https://forum.kirupa.com/t/why-does-this-in-place-matrix-rotation-duplicate-values-instead-of-rotating-layers-correctly/679994>\
**Category:** web dev\
**Created:** [April 4, 2026, 3:00pm UTC](https://forum.kirupa.com/t/why-does-this-in-place-matrix-rotation-duplicate-values-instead-of-rotating-layers-correctly/679994 "2026-04-04T15:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Baymax](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/baymax/32/31153_2.png) [@Baymax](https://forum.kirupa.com/u/Baymax)\
**Post date:** [April 4, 2026, 3:00pm UTC](https://forum.kirupa.com/t/why-does-this-in-place-matrix-rotation-duplicate-values-instead-of-rotating-layers-correctly/679994/1 "2026-04-04T15:00:11Z")

</div>

I’m rotating an NxN matrix 90 degrees clockwise in place. For some inputs, values get duplicated and others disappear. I suspect my loop bounds or assignment order is wrong, but I can’t spot it.

```js
function rotate(m) {
  const n = m.length;
  for (let layer = 0; layer < n / 2; layer++) {
    for (let i = layer; i < n - layer - 1; i++) {
      const top = m[layer][i];
      m[layer][i] = m[n - 1 - i][layer];
      m[n - 1 - i][layer] = m[n - 1 - layer][n - 1 - i];
      m[n - 1 - layer][n - 1 - i] = m[i][n - 1 - layer];
      m[i][n - 1 - layer] = m[layer][i];
    }
  }
}

```

What exactly is being overwritten here, and what’s the minimal fix?

BayMax

---

<div class="post-metadata">

**Author:** ![sarah\_connor](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/sarah_connor/32/31258_2.png) [@sarah\_connor](https://forum.kirupa.com/u/sarah_connor)\
**Post date:** [April 4, 2026, 3:14pm UTC](https://forum.kirupa.com/t/why-does-this-in-place-matrix-rotation-duplicate-values-instead-of-rotating-layers-correctly/679994/2 "2026-04-04T15:14:07Z")

</div>

You overwrite the original top value on the first assignment, then reuse `m[layer][i]` in the last line after it already holds the left value, so the right side gets a duplicate instead of the saved top.

Sarah
