# Rotate Array

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, \
the array

> \[1,2,3,4,5,6,7]

\
is rotated to

> \[5,6,7,1,2,3,4]

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

{% tabs %}
{% tab title="Scala" %}

```scala
def rotate(nums: Array[Int], k: Int) = {
  val r = k % nums.length
  reverse(nums, 0, nums.length - 1)
  reverse(nums, 0, r - 1)
  reverse(nums, r, nums.length - 1)
  nums
}

def reverse(nums: Array[Int], start: Int, end: Int): Array[Int] = {
  val diff = (end - start) / 2
  var tmp = 0
  for (i <- 0 until diff) {
    tmp = nums(start + i)
    nums(start + i) = nums(end - i)
    nums(end - i) = tmp
  }
  nums
}

/**
  * http://blog.thedigitalcatonline.com/blog/2015/05/13/99-scala-problems-16-20/#.V84U_ZMrJE5
  */
def rotate[A](n: Int, l: List[A]): List[A] = {
  val wrapn = if (l.isEmpty) 0 else n % l.length
  if (wrapn < 0) rotate(l.length + n, l)
  else l.drop(wrapn) ::: l.take(wrapn)
}

rotate(Array(1, 2, 3, 4, 5, 6, 7, 8, 9), 2)
```

{% endtab %}

{% tab title="Second Tab" %}

{% endtab %}
{% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://blog.bernardw.com/problems/rotate-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
