Math Student
Math Student

Reputation: 567

Last number in an array becomes first

I know that's easy, but I don't understand how I should do it.

 1 23 29 18 43 20 5 

to

 5 1 23 29 18 43 20 

I think we should use for-loop:

for (int i = 0; i < numbers.Count - 1; i++)
{

}

but I don't know what to do in it. Something like numbers[i] = numbers[i - 1] but it isn't working. I think there are some if checks which I miss.

Upvotes: 0

Views: 993

Answers (5)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can use this method to shift right:

void ShiftRight(int[] array, int count)
{
    var clone = (int[])array.Clone();
    for (var i = 0; i < array.Length; i++)
        array[(i + count) % array.Length] = clone[i];
}

And use it this way:

var a = new int[] { 1, 2, 3, 4 };
ShiftRight(a, 1);

Upvotes: 0

Here's a oneliner:

var numbers = new[] {1, 23, 29, 18, 43, 20, 5};
numbers = new[] {numbers.Last()}.Concat(numbers.Take(numbers.Length - 1)).ToArray();

This creates a new array containing the last element, then concatenates it with the original array excluding the last element.

Upvotes: 3

Steve
Steve

Reputation: 216273

The most straightforward way that comes to mind is a reverse loop.

int[] numbers = { 1, 23, 29, 18, 43, 20, 5};
int lastVal = numbers[numbers.Length - 1];
for (int i = numbers.Length -1; i > 0; i--)
    numbers[i] = numbers[i-1];
numbers[0] = lastVal;

Just looping from the end (after saving the last value) and moving "up" the values, finally replacing the first value with the last

Upvotes: 6

GeralexGR
GeralexGR

Reputation: 3582

You can perform a left rotation to the table by six positions on your case and create the requested new table

 int[] myArray = new int[] { 1, 23, 29, 18, 43, 20, 5 };
 var newArray = LeftRotationByD(myArray, 6);

and your function for the rotation would be:

 private static int[] LeftRotationByD(int[] a, int k)
        {
            int[] b = new int[a.Length];

            int index;
            int length = a.Length;
            int place;

            for (int i = 0; i < length; i++)
            {
                index = i - k;
                place = length + index;

                if (index >= 0) b[index] = a[i];
                else b[place] = a[i];
            }
            return b;
        }

Upvotes: 1

Dasanko
Dasanko

Reputation: 579

What you want to do is make another array of the same size as the original one, then assign the last element and loop through the array up to the previous to last element.

Something like this:

int[] original = {1, 23, 29, 18, 43, 20, 5};
int[] altered = new int[original.length];

altered[0] = original[original.length - 1];
for (int i = 1; i < original.length - 1; i++)
{
    altered[i] = original[i - 1];
}

Upvotes: 1

Related Questions