Home > Back-end >  How can I rotate this array?
How can I rotate this array?

Time:05-14

I have this code that works perfectly but in the opposite direction ( left ) I would like to rotate this array to the right, how can I do this?

 public int[] RotateArray(int[] A) {
    for(int i = 0 ;i < A.Length - 1;i  )
    {
       int aux = A[i 1];
       A[i 1] = A[i];
       A[i] = aux;

       // Aux = A[i];
    }
    return A;
}

The result that I've got:

[4,5,2,3] => [5,2,3,4]

Desired result:

[4,5,2,3] => [3,4,5,2]

CodePudding user response:

If you just want to shift the last to the first position, you can (mis)use Array.Copy, with source and destination referring to the same array.

int[] arr = { 4, 5, 2, 3 };
var last = arr[^1];
Array.Copy(arr, 0, arr , 1, arr.Length -1);
arr[0] = last; // -> now 3, 4, 5, 2

CodePudding user response:

Try iterating over the array from the back:

Note: I changed the method to be void since from the looks of it you were attempting an in-place solution anyway.

using System; 

public class Program {
    public static void RotateArray(int[] A) {
        if (A == null || A.Length <= 1) {
            return;
        }
        int lastElement = A[A.Length - 1];
        for (int i = A.Length - 1; i > 0; i--) {
            A[i] = A[i - 1];
        }
        A[0] = lastElement;
    }

    public static void Main(string[] args) {
        int[] array = new int[] { 4, 5, 2, 3 };
        Console.WriteLine("Before: [{0}]", string.Join(", ", array));
        RotateArray(array);
        Console.WriteLine("After: [{0}]", string.Join(", ", array));
    }
}

Output:

Before: [4, 5, 2, 3]
After: [3, 4, 5, 2]

CodePudding user response:

Here is a one-liner using Linq if you wish to go that route. (Note: No error checking but will work for arrays with at least one element).

Essentially you leverage Linq to get the first (N - 1) elements and prepend the last one.

var original = new int[] { 4,5,2,3 };

var rotated = 
    original
    .Take(original.Length - 1)
    .Prepend(
        original.Last())
    .ToArray();
  • Related