Reef Proctor
Reef Proctor

Reputation: 5

"rotate" values in array clockwise

Firstly thank you for taking the time to look at my question.

I have a csv file of letters for which i need to get the last letter of the array and move it to the start while "pushing" the other letters across

E.G.

--Source-- a,b,c,d,[e]

--Rotated-- e,a,b,c,d

            for (var i = 0; i < Array.Length - 1; i++)
            {
                temp = Array[Array.Length];
                Array[Array.Length] = Array[Array.Length - 1];
                Array[i + 1] = Array[i];
                Array[i] = temp;

            }

For this I am aware that not all characters would be effected but i cant think of a loop to get all values moved

Upvotes: 0

Views: 351

Answers (3)

Slaven Tojić
Slaven Tojić

Reputation: 3014

You can shift the numbers to right by using the modulo % operator :

int[] arr = { 1, 2, 3, 4, 5 };
int[] newArr = new int[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
    newArr[(i + 1) % newArr.Length] = arr[i];
}

newArr = {5,1,2,3,4}

DEMO HERE

EDIT:

Or you could make a method that shifts the numbers in your initial array without the need for creating a new array. The method rightShiftArray takes two parameters, the initial array arr an the number of shifts (shift) you want to perform:

public void rightShiftArray(ref int[] arr, int shift)
{
    for (int i = 0; i < shift; i++)
    {
        int temp;
        for (int j = 0; j < arr.Length - 1; j++)
        {
            temp = arr[j];
            arr[j] = arr[arr.Length - 1];
            arr[arr.Length - 1] = temp;
        }
    }
}

For example:

int[] arr = { 1, 2, 3, 4, 5 };

rightShiftArray(ref arr, 2);

The code above shifts the numbers in the initial array arr twice to the right and gives you the following output:

arr = { 4, 5, 1, 2, 3};

DEMO HERE

Upvotes: 1

Gene Byun
Gene Byun

Reputation: 188

Use Copy method:

int last = arr[arr.Length - 1];
Array.Copy(arr, 0, arr, 1, arr.Length - 1);
arr[0] = last;

Upvotes: 2

RezaNoei
RezaNoei

Reputation: 1479

if you doesn't want to allocate new array, you can use this code :

newValue = Array[Array.Length-1];
for (var i = 0; i < Array.Length; i++)
{
  temp = Array[i];
  Array[i] = newValue;
  newValue = temp;
}

Upvotes: 0

Related Questions