Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating right an array of int in c#?

I've got an homework assignment:

need to implement a function (RotateRight) that gets an array of INT and a number:

int[] res = RotateRight(new int[] { 1, 2, 3, 4, 5, 6 }, 2);
//so then res will be {5,6,1,2,3,4}

and return the array after rotating all of the items to the right according to the number that been given, In our case 2.

And I have to do this efficiently in terms of memory space.

my best idea is:

if the number that been given is x, to use a new int[] tmpArray in the size of x to copy all the last x items to it. then with a for loop to shift all the rest of the int to the right. And in the end to copy the items in the tmpArray to the begining of the original array.

Thanks in advance for any advice or help

like image 701
Erez Avatar asked Nov 12 '13 15:11

Erez


1 Answers

You can use the beauty of the Linq langage to return an IEnumerable without dealing with array size:

/// <summary>
/// Get c = a mod (b) with c in [0, b[ like the mathematical definition
/// </summary>
public static int MathMod(int a, int b)
{
    int c = ((a % b) + b) % b;
    return c;
}
public static IEnumerable<T> ShiftRight<T>(IList<T> values, int shift)
{
    for (int index = 0; index < values.Count; index++)
    {
        yield return values[MathMod(index - shift, values.Count)];
    }
}

Usage :

[TestMethod]
public void TestMethod1()
{
    var res = ShiftRight(new [] { 1, 2, 3, 4, 5, 6 }, 2).ToArray();
    Assert.IsTrue(res.SequenceEqual(new[] { 5, 6, 1, 2, 3, 4 }));
}
like image 181
Cyril Gandon Avatar answered Oct 04 '22 20:10

Cyril Gandon